判断数组的方法/判断JS数据类型的四种方法

参考文:

以下 3 个判断数组的方法,请分别介绍它们之间的区别和优劣Object.prototype.toString.call() 、 instanceof 以及 Array.isArray()

https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/23

判断JS数据类型的四种方法

https://www.cnblogs.com/onepixel/p/5126046.html

总结下来就是

使用mdn中的Array.isArray()方法判断

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray


假如不存在 Array.isArray(),则在其他代码之前运行下面的代码将创建该方法。

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

然后判断方法
if(
Array.isArray([1])){// true 即为数组
}

当检测Array实例时, Array.isArray 优于 instanceof,因为Array.isArray能检测iframes.