原生js 判断变量是一个数组

26次阅读

共计 268 个字符,预计需要花费 1 分钟才能阅读完成。

const arr = []
// 1. 最简单 ES5+
Array.isArray(arr)

// 2. 兼容性好的方法, 也很准确
Object.prototype.toString.call(arr) === ‘[object Array]’

// 3. 这个也不错
arr.constructor.name === ‘Array’

// 4. instance 不好用
console.log(a instanceof Array) // true
console.log(a instanceof Object) // true

// 5 找个数组独有的方法
arr.splice !== undefined

正文完
 0