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

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


当前回答

这是我的懒惰方法:

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边界工作,但对于我的用例来说,这不是问题。

其他回答

jQuery还提供了一个$.isArray()方法:

var a=[“a”,“AA”,“AAA”];if($.isArray(a)){alert(“a是一个数组!”);}其他{alert(“a不是数组!”);}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script>

//以简单的方式

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));

以下是我使用的:

function isArray(input) {
  if (input instanceof Array || Object.prototype.toString.call(input) === '[object Array]') {
        return true;
  } else return false;
}

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

这是我在考虑到以下评论的情况下对这个答案进行改进的尝试:

var isArray = myArray && myArray.constructor === Array;

它消除了if/else,并考虑了数组为空或未定义的可能性