Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of Array Differs In Internet Explorer With Trailing Comma

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.

like image 816
Ivan Avatar asked Jun 30 '11 21:06

Ivan


1 Answers

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

like image 122
mplungjan Avatar answered Oct 23 '22 04:10

mplungjan