如何检查对象是否为数组? [英] How can I check if an object is an array?

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

问题描述

我正在尝试编写一个接受字符串列表或单个字符串的函数.如果它是一个字符串,那么我想将它转换为一个只有一项的数组,这样我就可以循环遍历它而不必担心出错.

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

解决方案

在现代浏览器中,您可以:

Array.isArray(obj)

( Chrome 支持5、Firefox 4.0、Internet Explorer 9、Opera 10.5 和 Safari 5)

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

//只有在没有可用的本地实现时才实现if (typeof Array.isArray === '未定义') {Array.isArray = 函数(对象){return Object.prototype.toString.call(obj) === '[对象数组]';}};

如果你使用 jQuery,你可以使用 jQuery.isArray(obj)$.isArray(obj).如果您使用 Underscore.js,您可以使用 _.isArray(obj).

如果您不需要检测在不同帧中创建的数组,您也可以使用instanceof:

obj instanceof Array

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 so I can loop over it without fear of an error.

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

解决方案

In modern browsers you can do:

Array.isArray(obj)

(Supported by Chrome 5, Firefox 4.0, Internet Explorer 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]';
  }
};

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

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

obj instanceof Array

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

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