JS有哪些判断是否是数组的方法?

参考:JS判断是否是数组的四种做法

1、instanceof

let a = [];
a instanceof Array;  //true

instanceof运算符检测Array.prototype属性是否存在于变量a的原型链上.。
存在问题:

  1. prototype属性是可以修改的,所以并不是最初判断为true就一定永远为真
  2. 当我们的脚本拥有多个全局环境,例如html中拥有多个iframe对象,不同的全局环境会拥有自己的Array.prototype属性,Array.prototype !== window.frames[0].Array.prototype

2、constructor

let a = [];
a.constructor === Array // true

存在问题:
这种判断也会存在多个全局环境的问题,导致的问题与instanceof相同。

3、Object.prototype.toString.call()

Object.prototype.toString().call()可以获取到对象的不同类型,例如:

let a = [1,2,3]
Object.prototype.toString.call(a) === '[object Array]';//true
//检验是否是函数
let a = function () {};
Object.prototype.toString.call(a) === '[object Function]';//true
//检验是否是数字
let b = 1;
Object.prototype.toString.call(a) === '[object Number]';//true

甚至对于多全局环境时, Object.prototype.toString().call()也能符合预期处理判断。

4、Array.isArray() (最推荐)

let a = [1, 2, 3]
Array.isArray(a)  // true;

猜你喜欢

转载自blog.csdn.net/weixin_43912756/article/details/108354539