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

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


当前回答

以下是我使用的:

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

其他回答

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

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

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

函数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(input) {
  if (input instanceof Array || Object.prototype.toString.call(input) === '[object Array]') {
        return true;
  } else return false;
}

你可以试试这个:

var arr = []; (or) arr = new Array();
var obj = {}; (or) arr = new Object();

arr.constructor.prototype.hasOwnProperty('push') //true

obj.constructor.prototype.hasOwnProperty('push') // false

测试输入值是否为数组的简单函数如下:

function isArray(value)
{
  return Object.prototype.toString.call(value) === '[object Array]';
}

这可以跨浏览器使用,也可以使用较旧的浏览器。本文摘自T.J.Crowders的博客文章