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

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


当前回答

Use:

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

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

其他回答

我会制作一个函数来测试您正在处理的对象的类型。。。

函数whatAmI(me){return Object.pr原型.toString.call(me).split(/\W/)[2];}//测试控制台日志(whatAmI([“瞄准”,“@”]),whatAmI({生活:4,呼吸:4}),whatAmI(函数(ing){return ing+“到全局窗口”}),我(“要和你做什么?”));//输出:数组对象函数字符串

然后你可以写一个简单的if语句。。。

if(whatAmI(myVar) === "Array"){
    // do array stuff
} else { // could also check `if(whatAmI(myVar) === "String")` here to be sure
    // do string stuff
}

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

if (Array.isArray == null) {
  Array.isArray = (arr) => Object.prototype.toString.call(arr) === "[object Array]"
}

检查其原型和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 isArray = myArray && myArray.constructor === Array;

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

A = [1,2,3]
console.log(A.map == [].map)

为了寻找最短的版本,这是我到目前为止得到的。

注意,没有一个完美的函数能够始终检测所有可能的组合。与其期待一个神奇的工具,不如了解工具的所有能力和局限性。