I'm currently working with some data using Javascript that is in the form of an array. The array may contain an empty entry at the end, such as [1,2,]
. In Google Chrome and Firefox, the length of that example would be 2; however, in IE, the length is 3.
In short: Internet Explorer is giving a different length for an array in Javascript than Google Chrome and Firefox. Is there a way to standardize this behavior across all browsers?
Code:
var a = [1,];
alert(a.length);
EDIT:
A lot of answers are saying not to have a trailing comma, however, the data is given to me in this way.
Try removing empty elements:
Then it should work the same way in IE and other browsers.
Update: if the JS version is lower than 1.6, try this:
NEVER have trailing commas in IE. Period.
That goes for ARRAYs too
Javascript Browser Quirks - array.Length
To handle your edit this works (tested in in IE8):
if (a[a.length-1]==null) a.length--; // or a.pop()
For a safer test, please look at the other suggestion on this page: Length of Array Differs In Internet Explorer With Trailing Comma - DEMO HERE
By the way, never heard the words elision or elided before - learn something new here every day
No. IE incorrectly interprets a single trailing comma as an elision and adds one to the length when it shouldn't (ECMA-262 sect. 11.1.4).
Edit
To clear up the confusion here, IE treats a single trailing comma in an array literal (incorrectly) as an elision, which means it increments array's length property but does not create a property. In other words, given:
In IE, a.length is 3, but there is no property a[2]. So if an appropriate solution is to remove only elided members from the end of an array (which is likely the best solution if they are an issue), then:
will remove only elided members from the end of the array (that is, properties that don't exist), it will not remove them elsewhere, nor will it waste time iterating over the entire array (which can result in elided members being added as undefined). To add to Array.prototype:
Note that this is how Array.prorotype.filter works, it doesn't iterate over elided members (it uses a hasOwnProperty test and removes any elided mebers as part of filtering the array).