You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
附上 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).
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
所以,终极方法就是以下这个 👇
参考
The text was updated successfully, but these errors were encountered: