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
Prior to ECMAScript 5, however, distinguishing arrays from
nonarray objects was surprisingly difficult. The typeof
operator 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 The class Attribute) 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
=
Array
.
isArray
||
function
(
o
)
{
return
typeof
o
===
"object"
&&
Object
.
prototype
.
toString
.
call
(
o
)
===
"[object Array]"
;
};
This test ...
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.