JavaScript中判断数组的方式有哪些?

31 阅读2分钟

一、根据构造函数判断

(1)通过instanceof做判断

判断一个实例是否属于某构造函数

let arr = []
console.log(arr instanceof Array) // true

缺点:instanceof 底层原理是检测构造函数的 prototype 属性是否出现在某个实例的原型链上,如果实例的原型链发生变化,则无法做出正确判断

let arr = []
arr.__proto__ = function() {}
console.log(arr instanceof Array) // false

(2)通过constructor做判断

实例的构造函数属性 constructor 指向构造函数本身

let arr = []
console.log(arr.constructor === Array) // true

缺点:如果 arr 的 constructor 被修改,则无法做出正确判断。

let arr = []
arr.constructor = function() {}
console.log(arr.constructor === Array) // false

二、根据原型对象判断

(1)通过原型链__proto__做判断

实例的 __ proto __ 指向构造函数的原型对象

let arr = []
console.log(arr.__proto__ === Array.prototype) // true

缺点:如果实例的原型链的被修改,则无法做出正确判断

let arr = []
arr.__proto__ = function() {}
console.log(arr.__proto__ === Array.prototype) // false

(2)通过object.getPrototypeOf()做判断

Object 自带的方法,获取某个对象所属的原型对象

let arr = []
console.log(Object.getPrototypeOf(arr) === Array.prototype) // true

缺点:同上

(3)通过Array.prototype.isPrototypeOf()判断

Array 原型对象的方法,判断其是不是某个对象的原型对象

let arr = []
console.log(Array.prototype.isPrototypeOf(arr)) // true

缺点:同上

三、根据 Object 的原型对象判断

(1)通过object.prototype.toString.call()判断

Object 的原型对象上有一个 toString 方法,toString 方法默认被所有对象继承,返回 "[object type]" 字符串。但此方法经常被原型链上的同名方法覆盖,需要通过 Object.prototype.toString.call() 强行调用

let arr = []
console.log(Object.prototype.toString.call(arr) === '[object Array]') // true

这个类型就像胎记,一出生就刻在了身上,因此修改原型链不会对它造成任何影响。

let arr = []
arr.__proto__ = function() {}
console.log(Object.prototype.toString.call(arr) === '[object Array]') // true

(2)通过ES6的Array.isArray()做判断

Array.isArray() 是 ES6 新增的方法,专门用于数组类型判断,原理同上。

let arr = []
console.log(Array.isArray(arr)) // true

修改原型链不会对它造成任何影响。

let arr = []
arr.__proto__ = function() {}
console.log(Array.isArray(arr)) // true

综上所述

以上就是判断是否为数组的常用方法,还是 Array.isArray 最好用,还是ES6香!