Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a sane reason for this IE array.push bug?

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.

like image 349
Brian Deacon Avatar asked Dec 07 '22 04:12

Brian Deacon


1 Answers

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.

like image 94
nemisj Avatar answered Dec 19 '22 06:12

nemisj