检查对象是否是数组? [英] Check if object is an array?

查看:143
本文介绍了检查对象是否是数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个接受字符串列表或单个字符串的函数。如果它是一个字符串,那么我想将它转换为只有一个项目的数组。然后我可以循环它而不用担心错误。

I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item. Then I can loop over it without fear of an error.

那么如何检查变量是否为数组?

So how do I check if the variable is an array?

我已经完成了以下各种解决方案并创建了 jsperf test

I've rounded up the various solutions below and created a jsperf test.

推荐答案

在现代浏览器中,你可以做到

In modern browsers you can do

Array.isArray(obj)

支持 Chrome 5,Firefox 4.0,IE 9,Opera 10.5和Safari 5)

(Supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5)

为了向后兼容,您可以添加以下内容

For backward compatibility you can add the following

# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};

如果使用jQuery,可以使用 jQuery.isArray(obj) $。isArray(obj)。如果使用下划线,则可以使用 _。isArray(obj)

If you use jQuery you can use jQuery.isArray(obj) or $.isArray(obj). If you use underscore you can use _.isArray(obj)

如果您不需要检测数组在不同的框架中创建你也可以使用 instanceof

If you don't need to detect arrays created in different frames you can also just use instanceof

obj instanceof Array

这篇关于检查对象是否是数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆