判断数组的几种方法
instanceof
原型链查找
const arr1 = [1, 2, 3] const obj = { a: 1 } console.log(arr1 instanceof Array) //true console.log(obj instanceof Array) //false
Array.isArray()
ES6新方法,用于确定传递的值是否为数组
console.log(Array.isArray([1, 2])) //true console.log(Array.isArray({ a: 2 })) //false
Array.isArray优于instanceof,Array.isArray能检测到iframes,如下
var iframe = document.createElement('iframe') document.body.appendChild(iframe) var xArray = window.frames[window.frames.length - 1].Array var arr = new xArray(1, 2, 3) console.log(Array.isArray(arr)) //true console.log(arr instanceof Array) //false (不能检测到iframes中的数组)
constructor
构造函数类型判断
console.log(arr1.constructor === Array) //true console.log(obj.constructor === Array) //false
toString
console.log(Object.prototype.toString.call(arr1) === '[object Array]') //true console.log(Object.prototype.toString.call(obj) === '[object Array]') //false