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

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


当前回答

您可以使用isArray方法,但我更愿意检查:

Object.getPrototypeOf(yourvariable)==Array.prototype

其他回答

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

函数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
}

这是所有方法中速度最快的(所有浏览器都支持):

function isArray(obj){
    return !!obj && obj.constructor === Array;
}
A = [1,2,3]
console.log(A.map == [].map)

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

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

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

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