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

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


当前回答

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

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 someFunc(arg) {
    var arr = (typeof arg == "string") ? [arg] : arg;
}

如果您知道对象没有concat方法,可以使用以下方法。

var arr=[];if(arr.concat类型==“函数”){console.log(“这是一个数组”);}

Use:

var is_array = function (value) {
   return value &&
     typeof value === 'object' &&
     typeof value.length === 'number' &&
     typeof value.splice === 'function' &&
    !(value.propertyIsEnumerable('length'));
};

这个函数取自《JavaScript:TheGoodParts》一书,非常适合我。

您可以使用Array.isArray()。这里是一个polyfill:

if (Array.isArray == null) {
  Array.isArray = (arr) => Object.prototype.toString.call(arr) === "[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 */};