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

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


当前回答

//以简单的方式

const arr = [1, 2, 3];
const obj = { message: 'nice' };
const str = 'nice';
const empty = null;

console.log(Array.isArray(arr));
console.log(Array.isArray(obj));
console.log(Array.isArray(str));
console.log(Array.isArray(empty));

其他回答

最好的做法是使用构造函数进行比较,如下所示

if(some_variable.constructor === Array){
  // do something
}

您也可以使用其他方法,如typeOf,将其转换为字符串,然后进行比较,但将其与dataType进行比较总是更好的方法。

Array.isArray工作速度很快,但并非所有版本的浏览器都支持它。

因此,您可以为其他人创建例外,并使用通用方法:

    Utils = {};
    Utils.isArray = ('isArray' in Array) ?
        Array.isArray :
        function (value) {
            return Object.prototype.toString.call(value) === '[object Array]';
        }

我见过的最佳解决方案是用跨浏览器替换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 */};

检查其原型和Array.isArray之间存在差异:

function isArray(obj){
    return Object.getPrototypeOf(obj) === Array.prototype
}

此函数将直接检查obj是否为数组。

但对于此代理对象:

var arr = [1,2,3]

var proxy = new Proxy(arr,{})

console.log(Array.isArray(proxy)) // true

Array.isArray将其作为Array。

你可以试试这个:

var arr = []; (or) arr = new Array();
var obj = {}; (or) arr = new Object();

arr.constructor.prototype.hasOwnProperty('push') //true

obj.constructor.prototype.hasOwnProperty('push') // false