2010-05-19

Javascript Array Length

Try the following code in different browsers:

var array = [1,2,3,4,]; //note the trailing ','

alert(array.length);

IE gives 5, Firefox and Google Chrome gives 4. Guess who gives the correct answer? It may be a little surprise. Congrats IE. Here's the spec from ECMAScript standard:

Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined.

No comments:

Post a Comment