JavaScript 数组类型判断

231 阅读1分钟

1. instanceof

通过 instanceof 运算符判断数组构造函数的 prototype 是否出现在该对象的原型链中,返回 boolean 值

[] instanceof Array; //true

代码解析:instanceof 运算符检测 Array.prototype 属性是否存在于 [] 的原型链上 [].__proto__ === Array.prototype,返回 true

存在问题:Symbol.hasInstance 自定义 instanceof 的行为,所以 instanceof 不是百分百可信的;构造函数的 prototype 属性是可以修改的

2. constructor

通过实例的 constructor 属性,因为实例的 constructor 属性指向其构造函数

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

3. Object.prototype.toString.call()

通过 Object.prototype.toString.call() 判断

Object.prototype.toString.call([]) === '[object Array]'; // true

他强大的地方在于不仅仅可以检验是否为数组,比如是否是一个函数,是否是数字等等

4. Array.isArray()

Array.isArray() 用于确定传递的值是否是一个数组,返回一个布尔值。

Array.isArray([]) // true