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

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


当前回答

检查其原型和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。

其他回答

这是我的懒惰方法:

if (Array.prototype.array_ === undefined) {
  Array.prototype.array_ = true;
}

// ...

var test = [],
    wat = {};

console.log(test.array_ === true); // true
console.log(wat.array_ === true);  // false

我知道“搞乱”原型是一种亵渎,但它的性能明显优于推荐的toString方法。

注意:这种方法的一个缺点是它不能跨iframe边界工作,但对于我的用例来说,这不是问题。

//以简单的方式

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

我现在找到了最短的答案:

变量x=[1,2,3]控制台日志(x.map?1:0)

在现代浏览器中,您可以执行以下操作:

Array.isArray(obj)

(支持Chrome 5、Firefox 4.0、Internet Explorer 9、Opera 10.5和Safari 5)

为了实现向后兼容性,可以添加以下内容:

// Only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};

如果使用jQuery,可以使用jQuery.isArray(obj)或$.isArra(obj)。如果使用Undercore.js,可以使用_.isArray(obj。

如果不需要检测在不同帧中创建的阵列,也可以只使用instanceof:

obj instanceof Array

异国情调的

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

x===x+''

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