Length of Array Differs In Internet Explorer With

2019-02-11 22:08发布

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.

3条回答
聊天终结者
2楼-- · 2019-02-11 22:31

Try removing empty elements:

a = a.filter(function(){return true});

Then it should work the same way in IE and other browsers.

Update: if the JS version is lower than 1.6, try this:

Array.prototype.clean = function() {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == undefined) {
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};


a.clean()
查看更多
\"骚年 ilove
3楼-- · 2019-02-11 22:44

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

查看更多
Melony?
4楼-- · 2019-02-11 22:45

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:

var a = [0,1,];

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:

function tidyTrailingElisions(array) {
  var i = array.length;
  while (!array.hasOwnProperty(--i)) {}
  array.length = ++i;
  return array;
}

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:

Array.prototype.tidyTrailingElisions = function() {
  var i = this.length;
  while ( !this.hasOwnProperty(--i)) {}
  this.length = ++i;
  return this;
};

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

查看更多
登录 后发表回答