简体   繁体   中英

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:

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.

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?).

That's not a bug. That's exactly how it should behave. Microsoft did that on purpose. If you want an array with only 4 items, get rid of the last comma. Simple as that.

If the results you're after is to have an extra, undefined value at the end, you're in luck. Even without the comma, it'll be undefined. It, and every single number after 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM