jcz1206

参考文:

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

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

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

Polyfill

假如不存在 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.

分类:

技术点:

相关文章:

  • 2021-11-20
  • 2021-11-20
  • 2021-11-20
  • 2022-01-02
  • 2021-09-09
  • 2021-11-20
  • 2019-06-03
  • 2021-11-20
猜你喜欢
  • 2021-11-20
  • 2021-11-20
  • 2022-01-03
  • 2021-11-20
  • 2021-02-19
  • 2021-11-20
  • 2021-11-20
相关资源
相似解决方案