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

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


当前回答

以下是我使用的:

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

其他回答

Array.isArray工作速度很快,但并非所有版本的浏览器都支持它。

因此,您可以为其他人创建例外,并使用通用方法:

    Utils = {};
    Utils.isArray = ('isArray' in Array) ?
        Array.isArray :
        function (value) {
            return Object.prototype.toString.call(value) === '[object 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));

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

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

这个问题只有一行解决方案

x instanceof Array

其中x是变量,如果x是数组,则返回true,如果不是,则返回false。

我首先检查您的实现是否支持isArray:

if (Array.isArray)
    return Array.isArray(v);

也可以尝试使用instanceof运算符

v instanceof Array