我正在尝试编写一个接受字符串列表或单个字符串的函数。 如果是字符串,那么我想将其转换为仅包含一项的数组。 然后,我可以循环浏览它而不必担心错误。
那么,如何检查变量是否为数组?
我整理了以下各种解决方案,并创建了jsperf测试 。 它们都非常快,因此只需使用Array.isArray
-现在得到了很好的支持,并且可以跨框架使用 。
#1楼
我知道,人们正在寻找某种原始的javascript方法。 但是,如果您想少考虑一下,请看这里: http : //underscorejs.org/#isArray
_.isArray(object)
如果object是Array,则返回true。
(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true
#2楼
我将提供一个功能来测试您正在处理的对象的类型...
function whatAmI(me){ return Object.prototype.toString.call(me).split(/\\W/)[2]; } // tests console.log( whatAmI(["aiming","@"]), whatAmI({living:4,breathing:4}), whatAmI(function(ing){ return ing+" to the global window" }), whatAmI("going to do with you?") ); // output: Array Object Function String
那么您可以编写一个简单的if语句...
if(whatAmI(myVar) === "Array"){
// do array stuff
} else { // could also check `if(whatAmI(myVar) === "String")` here to be sure
// do string stuff
}
#3楼
简单的功能检查一下:
function isArray(object)
{
if (object.constructor === Array) return true;
else return false;
}
#4楼
正如MDN 在这里所说:
使用Array.isArray或Object.prototype.toString.call区分常规对象和数组
像这样:
Object.prototype.toString.call(arr) === '[object Array]'
,或Array.isArray(arr)
#5楼
Array.isArray可以快速运行,但是并非所有版本的浏览器都支持。 因此,您可以为其他人设置例外并使用通用方法:
Utils = {};
Utils.isArray = ('isArray' in Array) ?
Array.isArray :
function (value) {
return Object.prototype.toString.call(value) === '[object Array]';
}
#6楼
这是我的懒惰方法:
if (Array.prototype.array_ === undefined) {
Array.prototype.array_ = true;
}
// ...
var test = [],
wat = {};
console.log(test.array_ === true); // true
console.log(wat.array_ === true); // false
我知道它“牺牲”了原型,但是