Google Groups

myArray instanceof Array fails after passing to a different page


Douglas Crockford Sep 23, 2003 5:15 PM
Posted in group: comp.lang.javascript
> I have a page with a series of child pages loaded into an iframe.  When I
> move from page to page, I store an object containing the child's control
> data in a variable on the main page, then use that data to populate the
> controls when the child page is opened again.
>
> One of these objects contains an Array, and the page reloads fine using
> myArray[0], myArray[1], etc...  But when I try perform some array methods
> on it (i.e.slice) ... it does not recognize it as an array.
>
> By checking "myArray instanceof Array", I have determined that the object
> is seen as an array until it is passed to the parent page.  Then "myArray
> instanceof Array" fails.
>
> Does anybody know why this is?  And/Or how I can get around it?

When you say 'Array', you are talking about 'window.Array'. 'window' is the
browser's context object, and you get one per page (or frame). All of the arrays
created within a context will have their constructor property set to
'window.Array'.

An array created in a different context has a different window.Array, so your
test

    myArray instanceof Array

fails. The ECMAScript standard does not discuss multiple contexts, even though
virtually all implementations support them. The ECMAScript standard also fails
to provide a reliable technique for testing the type of arrays. The obvious
thing would have been

    typeof myArray == 'array'

except that unfortunately, it turns out that

    typeof myArray == 'object'

which not very useful.

You might try testing for the presence of a well-know array method.

    typeof myArray.sort == 'function'

This is not infallible, but it is better than the useless instanceof operator.

www.crockford.com/javascript/javascript.html