views:

141

answers:

3

Note: Edited the sample to reflect my actual problem, which was a trailing comma in the array initialization.

Seems that a mixture of raw array initialization and array.push can cause the indexes to get all whacky.

I do this:

var iFeelLikeIt = true;
var items = ["thing1", "thing2",];
if (iFeelLikeIt) {
  items.push("thing3");
}
items.push("thing4");

In IE7, (haven't checked 6 or 8), my array looks like:

  • thing1
  • thing2
  • undefined
  • thing3
  • thing4

Actually, it looks more like a keyed-by-number dictionary, with keys for 0,1,3,4.

I've changed my code to just initializing an empty array and pushing everything onto it as needed, and it behaves sanely. But was wondering if anybody knew of a valid reason for this behavior? Or something that at least smells like a lame excuse for a valid reason.

A: 

Works fine in IE8. I don't have any machines with IE7 handy to reproduce, and Google didn't turn up anything. Not really sure what's going on. Maybe a off-by-one bug between where the top of the array pointer is after initialization, and where push() is expecting it to be? That would be my valid-reason-smelling lame excuse.

jdmichal
+11  A: 

First of all, if i run your example it shows an error that thing1 is undefined. I guess you wanted to make it as string? Then, if I try to do this, iFeelLikeIt throws also error, cause it's undefined.

I assume you wrote in your code this :

var items = ["thing1", "thing2",];

Check the last comma at the end of the array. IE interprets it as the new undefined value, which will create array with next values:

thing1, thing2 and undefined value.

Nothing more than that.

nemisj
I would definitely check for an extraneous comma since nemisj is correct about IE interpreting that as an undefined value.
sberry2A
IE typically crashes when superfluous commas are encountered
Justin Johnson
I'd also guess this
Dan Beam
@Justin Johnson, not when declaring an array. Try alert(["a","b",].length); and see in action.
nemisj
So color me impressed that you guessed my bug when I reproduced it incorrectly. My actual code was too complicated to just post, but it did indeed have a trailing comma (camouflaged by the too-complicated code).
Brian Deacon
Hah. That's what I get for trying to reproduce by writing my own code for it. Completely missed that.
jdmichal
A: 

I believe that your problem may be in your expression that is replaced by iFeelLikeIt. However you have not included enough information to resolve your specific problem. Perhaps if you posted working code we could resolve your issue/bug/problem.

ThatGuyYouKnow