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

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


当前回答

function isArray(value) {
    if (value) {
        if (typeof value === 'object') {
            return (Object.prototype.toString.call(value) == '[object Array]')
        }
    }
    return false;
}

var ar = ["ff","tt"]
alert(isArray(ar))

其他回答

以下是我使用的:

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

您可以检查变量的类型是否为数组;

var myArray=[];

if(myArray instanceof Array)
{
....
}

//以简单的方式

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进行比较总是更好的方法。

这是我的懒惰方法:

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