JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

7.10 Array Type

7.10 Array Type

We’ve seen throughout this chapter that arrays are objects with some special behavior. Given an unknown object, it is often useful to be able to determine whether it is an array or not. In ECMAScript 5, you can do this with the Array.isArray() function:

Array.isArray([]) // => true Array.isArray({}) // => false

7.10 Array Type | 157

Prior to ECMAScript 5, however, distinguishing arrays from nonarray objects was surprisingly difficult. The typeofoperator does not help here: it returns “object” for arrays (and for all objects other than functions). The instanceof operator works in simple cases:

[] instanceof Array // => true ({}) instanceof Array // => false

The problem with using instanceof is that in web browsers, there can be more than one window or frame open. Each has its own JavaScript environment, with its own global object. And each global object has its own set of constructor functions. Therefore an object from one frame will never be an instance of a constructor from another frame. While interframe confusion does not arise often, it is enough of a problem that the instanceof operator is not deemed a reliable test for arrays.

The solution is to inspect the class attribute (see §6.8.2 ) of the object. For arrays, this attribute will always have the value “Array”, and we can therefore write an isArray() function in ECMAScript 3 like this:

var isArray = Function.isArray || function(o) {

return typeof o === "object" && === "[object Array]";


友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1