首页 > 技术文章 > 原生js 判断变量是一个数组

lovellll 2019-01-05 18:13 原文


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


推荐阅读