15

I'm experiencing an odd behavior (maybe it isn't odd at all but just me not understanding why) with an javascript array containing some objects.

Since I'm no javascript pro, there might very well be clear explanation as to why this is happening, I just don't know it.

I have javascript that is running in a document. It makes an array of objects similar to this:

var myArray = [{"Id":"guid1","Name":"name1"},{"Id":"guid2","Name":"name2"},...];

If I print out this array at the place it was created like JSON.stringify(myArray), I get what I was expecting:

[{"Id":"guid1","Name":"name1"},{"Id":"guid2","Name":"name2"},...]

However, if I try to access this array from a child document to this document (a document in a window opened by the first document) the array isn't an array any more. So doing JSON.stringify(parent.opener.myArray) in the child document will result in the following:

{"0":{"Id":"guid1","Name":"name1"},"1":{"Id":"guid2","Name":"name2"},...}

And this was not what I was expecting - I was expecting to get the same as I did in teh parent document.

Can anyone explain to me why this is happening and how to fix it so that the array is still an array when addressed from a child window/document?

PS. the objects aren't added to the array as stated above, they are added like this:

function objTemp()
{
    this.Id = '';
    this.Name = '';
};

var myArray = [];

var obj = new ObjTemp();
obj.Id = 'guid1';
obj.Name = 'name1';

myArray[myArray.length] = obj;

If that makes any difference.

Any help would be much appreciated, both for fixing my problem but also for better understanding what is going on :)

7
  • What browser are you testing on? I remember there was a thread where exactly the same behavior happened in IE but not in FF. Can you provide a JSFiddle to test that issue? See here. Commented May 2, 2012 at 9:25
  • I cannot reproduce. In which browser did you test that? Did you use a JSON library? Commented May 2, 2012 at 9:39
  • I'm testing in IE because it is a requirement. Personly I wouldn't pick IE but it is not up to me. I'm only using json in this example to stringify my alert. I'm not using any json library for the code that produces the behavior. Commented May 2, 2012 at 9:59
  • If I do alert(typeof myArray.sort) in the document creating the array i get 'function'. If I do alert(typeof parent.opener.myArray.sort) in the child document I get 'object' and yes this is IE. It looks exactly like this is the same issue as is the case in the post you linked. So what to do then? The other post doesn't provide an ansver or solution. Commented May 2, 2012 at 10:18
  • Don't use IE :-) Does the array-detection by Object.prototype.toString.apply(value) === '[object Array]' work? Then you could use a JSON lib that uses this method. Commented May 2, 2012 at 10:30

2 Answers 2

8

The very last line might be causing the problem, have you tried replacing myArray[myArray.length] = obj; with myArray.push(obj);? Could be that, since you're creating a new index explicitly, the Array is turned into an object... though I'm just guessing here. Could you add the code used by the child document that retrieves myArray ?

Edit

Ignore the above, since it won't make any difference. Though, without wanting to boast, I was thinking along the right lines. My idea was that, by only using proprietary array methods, the interpreter would see that as clues as to the type of myArray. The thing is: myArray is an array, as far as the parent document is concerned, but since you're passing the Array from one document to another, here's what happens:

An array is an object, complete with it's own prototype and methods. By passing it to another document, you're passing the entire Array object (value and prototype) as one object to the child document. In passing the variable between documents, you're effectively creating a copy of the variable (the only time JavaScript copies the values of a var). Since an array is an object, all of its properties (and prototype methods/properties) are copied to a 'nameless' instance of the Object object. Something along the lines of var copy = new Object(toCopy.constructor(toCopy.valueOf())); is happening... the easiest way around this, IMO, is to stringency the array withing the parent context, because there, the interpreter knows it's an array:

//parent document
function getTheArray(){ return JSON.stringify(myArray);}
//child document:
myArray = JSON.parse(parent.getTheArray());

In this example, the var is stringified in the context that still treats myArray as a true JavaScript array, so the resulting string will be what you'd expect. In passing the JSON encoded string from one document to another, it will remain unchanged and therefore the JSON.parse() will give you an exact copy of the myArray variable.

Note that this is just another wild stab in the dark, but I have given it a bit more thought, now. If I'm wrong about this, feel free to correct me... I'm always happy to learn. If this turns out to be true, let me know, too, as this will undoubtedly prove a pitfall for me sooner or later

Sign up to request clarification or add additional context in comments.

6 Comments

No, that syntax is perfectly valid to create a new member of an Array. Although .push() is more descriptive (and I like it better), the assignment also works and is even a bit faster.
I don't think the array is invalid due to the way I add items to it, as I also stated in the post, if I try to alert the array stringified it looks correct (aka it is not an object but an array). If I do the exact same thing from the child document the array is now an object, not only if I alert the var stringified but the code that was supposed to work with the array throws an error because e.g. myArray[0].Id is null (because it doesn't exist of cause).
Stringifying the array on the parent page and then parsing the string on the child page did the trick, and thanks for the rather thorough answer, I learned something too :)
In my case, replacing .push(x) with .[i] = x did actually preserve the .slice method somehow. Whereas using stringify gave me a strange unexpected token A on localhost:1 O_o
6 years later, I still stumbled upon this. with ECMA 6, is there any other option ?
|
1

Check out the end of this article http://www.karmagination.com/blog/2009/07/29/javascript-kung-fu-object-array-and-literals/ for an example of this behavior and explanation.

Basically it comes down to Array being a native type and each frame having its own set of natives and variables.

From the article:

// in parent window
var a = [];
var b = {};
//inside the iframe
console.log(parent.window.a); // returns array
console.log(parent.window.b); // returns object

alert(parent.window.a instanceof Array); // false
alert(parent.window.b instanceof Object); // false
alert(parent.window.a.constructor === Array); // false
alert(parent.window.b.constructor === Object); // false

Your call to JSON.stringify actually executes the following check (from the json.js source), which seems to be failing to specify it as an Array:

        // Is the value an array?
        if (Object.prototype.toString.apply(value) === '[object Array]') {
           //stringify

3 Comments

Na, it seems exactly not to use Array.isArray, which would work cross-window, instead it would use instanceof to cause the descripted behaviour.
Oh yeah this looks like it is browser specific now since json2.js defaults to just executing the browser's native version of stringify if one is available (and it should be in all modern browsers)
I mean the code Object.prototype.toString.apply(value) === '[object Array]' would not fail, despite you say so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.