0
var arr=["test"]; for(var e in arr) console.log(e);

in IE11's console it outputs:

0 contains remove clear add addAll(all properties)

and in chrome's console only outputs 0, which is expected.

how to fix it in IE? I know I can use for(var i=0;i<arr.length;i++) to solve it. but I just wonder why IE outputs all the properties.

enter image description here

enter image description hereenter image description here

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0day
  • 103
  • 1
  • 10
  • @ssube questions are duplicates, not answers. Even if the _answer_ is the same, only close a duplicate if the _question_ is the same. – Matt Ball Jan 30 '15 at 17:32
  • @MattBall Fixed my comment phrasing. The question is phrased differently, but is the same issue. Not quite sure if it's a dupe or not, right on the edge. – ssube Jan 30 '15 at 17:34
  • If you add properties via Object.defineProperty you can prevent them from being enumerated in the list. IE is doing it right. – Mouser Jan 30 '15 at 17:36
  • Most likely the page has created some polyfills for non-existing properties in IE. `for..in` is expected to iterate the properties in the prototype chain too. If Chrome doesn't iterate them (which I doubt), it would clearly be a bug in Chrome. – Teemu Jan 30 '15 at 17:59

2 Answers2

2

using IE11 and looks ok to me

enter image description here

if you want more control use Array.prototype.forEach method.It accepts a callback which have three parameters.They are element,their index and the array itself.Try

var arr=["test",'ball'];arr.forEach(function(element,index){
   console.log(index);
});
AL-zami
  • 8,902
  • 15
  • 71
  • 130
1

Use the hasOwnProperty method.

Example:

var arr = ["test"];
for (var e in arr) {
    if (arr.hasOwnProperty(e)) {
        console.log(e);
    }
}

Good explanation on why this is necessary: https://stackoverflow.com/a/12017703/1387396

Details on the hasOwnProperty method and its use in for .. in loops: Object.prototype.hasOwnProperty() - JavaScript | MDN

Community
  • 1
  • 1
aaronk6
  • 2,701
  • 1
  • 19
  • 28