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([])// => trueArray.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:
[]instanceofArray// => true({})instanceofArray// => 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:
varisArray=Array.isArray||function(o){returntypeofo==="object"&&Object.prototype.toString.call(o)==="[object Array]";};
This test ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access