附上 Categorizing values in JavaScript 的一段原话:
Array.isArray() exists because of one particular problem in browsers: each frame has its own global environment. An example: Given a frame A and a frame B (where either one can be the document). Code in frame A can pass a value to code in frame B. Then B code cannot use instanceof Array to check whether the value is an array, because its B Array is different from the A Array (of which the value could be an instance).
看代码:
var iframe = document.createElement('iframe')
document.body.appendChild(iframe)
var xArray = window.frames[window.frames.length - 1].Array
var xarr = new xArray()
var arr = new Array()
// 不同页面,结果并非我们所预期的 true,而是 false 哦!
console.log(xarr instanceof Array) // false
console.log(xarr.constructor === Array) // false
// 同页面才是 true 哦!
console.log(arr instanceof Array) // true
console.log(arr.constructor === Array) // true
JavaScript 判断数组的几种方法及其利弊。
1. typeof
对于 Function、String、Number、Undefined 等几种类型的对象来说,他完全可以胜任。但是为 Array 时:
所以不能使用
typeof
来判断。2. instanceof
instanceof
运算符用于检测构造函数的prototype
属性是否出现在某个实例对象的原型链上。3. 原型链(constructor)
一般情况下,除了
undefined
和null
,其它都能使用constructor
判断类型。但是某些情况下,判断是不准确的,比如:
使用 instanceof 和 constructor 的局限性:
看代码:
4. Array.isArray
鉴于以上原因,ES5 标准提供的一个判断数组方法
isArray()
,其原理也是通过Object.prototype.toString()
判断对象的内部属性[[Class]]
是否为"Array"
,以达到判断数组的目的。5. Object.prototype.toString
所以,终极方法就是以下这个 👇
参考