我正在尝试编写一个函数,它要么接受字符串列表,要么接受单个字符串。如果它是一个字符串,那么我想把它转换成一个只有一个项的数组,这样我就可以在上面循环,而不用担心出错。

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


当前回答

我首先检查您的实现是否支持isArray:

if (Array.isArray)
    return Array.isArray(v);

也可以尝试使用instanceof运算符

v instanceof Array

其他回答

检查对象是否为数组的最简单快捷的方法。

var arr = [];
arr.constructor.name === 'Array'  // Returns true;

or

arr.constructor === Array // Returns true;

或者您可以创建一个实用函数:

const isArray = (obj) => !!obj && obj.constructor === Array;

用法:

isArray(arr); // Returns true

这是所有方法中速度最快的(所有浏览器都支持):

function isArray(obj){
    return !!obj && obj.constructor === Array;
}

您可以使用isArray方法,但我更愿意检查:

Object.getPrototypeOf(yourvariable)==Array.prototype

这是我的懒惰方法:

if (Array.prototype.array_ === undefined) {
  Array.prototype.array_ = true;
}

// ...

var test = [],
    wat = {};

console.log(test.array_ === true); // true
console.log(wat.array_ === true);  // false

我知道“搞乱”原型是一种亵渎,但它的性能明显优于推荐的toString方法。

注意:这种方法的一个缺点是它不能跨iframe边界工作,但对于我的用例来说,这不是问题。

我见过的最佳解决方案是用跨浏览器替换typeof。检查Angus Croll的解决方案。

TL;DR版本在下面,但这篇文章对这个问题进行了很好的讨论,所以如果您有时间,应该阅读它。

Object.toType = function(obj) {
    return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
// ... and usage:
Object.toType([1,2,3]); //"array" (all browsers)

// or to test...
var shouldBeAnArray = [1,2,3];
if(Object.toType(shouldBeAnArray) === 'array'){/* do stuff */};