JavaScript判断数组的五种方法

1. instanceof

使用instanceof运算符判断,instanceof

const arr= []
instanceof arr === Array // true
复制代码

2. Array.isArray

使用ES5的方法Array.isArray关键词判断,函数详情

const arr = []
Array.isArray(arr) // true

const obj = {}
Array.isArray(obj) // false
复制代码

3. Object.prototype.isPrototypeOf

使用Object的原型方法isPrototypeOf,判断两个对象的原型是否一样,
isPrototypeOf() 方法用于测试一个对象是否存在于另一个对象的原型链上。

const arr = []
Object.prototype.isPrototypeOf(arr, Array.prototype) // true
复制代码

4. Object.getPrototypeOf

Object.getPrototypeOf() 方法返回指定对象的原型(内部[[Prototype]]属性的值)。

const arr = []
Object.getPrototypeOf(Array.prototype) === Array.prototype // true
复制代码

5. Object.prototype.toString

借用Object原型的call或者apply方法,调用toString()是否为[object Array]

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

const obj = {}
Object.prototype.toString.call([]) // "[object Object]"
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享