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

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


当前回答

var a = [], b = {};

console.log(a.constructor.name == "Array");
console.log(b.constructor.name == "Object");

其他回答

检查此项的简单函数:

function isArray(object)
{
    return object.constructor === Array;
}

异国情调的

您想检查参数是否为字符串,所以请尝试

x===x+''

设isStr=x=>x===x+'';console.log(isStr([]));console.log(isStr([“aa”,“bb”]));console.log(isStr(“”));console.log(isStr(“abc”));

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))
var a = [], b = {};

console.log(a.constructor.name == "Array");
console.log(b.constructor.name == "Object");

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

Object.getPrototypeOf(yourvariable)==Array.prototype