Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE9 JavaScript array initialization bug

Apparently JS implementation in IE9 contains (IMO, critical) bug in handling array literals.

In IE9 in some cases this code:

var a = [1,2,3,4,];

will create array of length 5 with last element equals to undefined.

Here are two versions of my KiTE engine test pages:

  • http://terrainformatica.com/kite/test-kite.htm - works in IE9
  • http://terrainformatica.com/kite/test-kite-ie9-bug.htm - fails in IE9

The only difference is that first document contains data.contacts property initialized as [1,2,3,4] and second one as [1,2,3,4,].

Internal IE debugger reports that data.contacts array contains 5 elements in second case. Without debugger this code fails at line 98 in kite.js (trying to get property of undefined - fifth element of that data.content array )

Questions:

  1. How and where people usually report bugs in IE?
  2. Have you seen anything similar to this problem? I am looking for simplest case where this problem is reproducible.

Update: here is the test http://jsfiddle.net/hmAms/ where all browsers (IE9 included) agree on the fact that var a = [1,2,3,4,]; is of length 4.

like image 472
c-smile Avatar asked Jun 01 '11 05:06

c-smile


1 Answers

A single trailing comma in an array literal should be ignored. Two trailing commas is an elision and should add one to the array's length. So:

alert( [1,2,3,4,].length );   // 4

alert( [1,2,3,4,,].length );  // 5

Some versions of IE (< 9?) treat the single trainling comma as an elison and incorrectly add one to length, so the results above are 5 and 6 respsectively. That is inconsistent with ECMA-262 §11.1.3 and therefore is a bug.

The purpose of an elision is to increase array length without creating a extra property or assigning directly to length, so:

var x = [,1,,];

is equivalent to:

var x = new Array(3);
x[1] = 1;

The result in both cases should be an array with length 3 and one property named '1' with value 1. The leading comma and trailing comma pair are elisions, they only affect the length, they do not create properties. IE interprets the leading comma correctly but incorrectly interprets both trailing commas as elisions, incrementing the length by 1 too many.

var x = [,1,,3,,];
var s = 'length: ' + x.length;

for (var p in x) {
  s += '\nindex ' + p + ' has value ' +  x[p]; 
}
alert(s);

The result should be:

length: 5
index 1 has value 1
index 3 has value 3

Incidentally, this bug has probably been around since IE allowed array literals, version 4 at least (1997?).

like image 140
RobG Avatar answered Nov 11 '22 09:11

RobG