0
this.someArray = [1,2,3,4,5]
for(var i in this.someArray){console.log(this.someArray[i]);}

It not only loops through the array elements but also junk like 'remove'. I don't want to abandon the enhanced loop and use the regular loop (as it is inconvenient). Is there a way to loop only through the array contents?

ppecher
  • 1,978
  • 4
  • 19
  • 30

4 Answers4

2

Never loop through an array like that, do this:

for(var i=0;i<this.someArray.length;i++){...}

"I don't want to abandon the enhanced loop and use the regular loop (as it is inconvenient)"

Sorry, but as far as I know this is the right way to loop through an array...

JCOC611
  • 19,111
  • 14
  • 69
  • 90
2

Your loop is catching the methods and properties of Array.prototype in addition to the array's contents. Like JCOC611 said, it is usually better to loop through arrays the "right" way, but if you don't want to do that, you can use the array's hasOwnProperty function to check if a property is actually in the array or if it is part of Array.prototype:

this.someArray = [1, 2, 3, 4, 5];
for (var i in this.someArray) {
    if (this.someArray.hasOwnProperty(i)) {
        console.log(this.someArray[i]);
    }
}

See this question for more details: Why is using "for...in" with array iteration a bad idea?

Also, this blog post has lots of information: http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/

Community
  • 1
  • 1
jhartz
  • 1,566
  • 9
  • 12
2

For an array, using an old-fashioned for-loop with an index is probably the sensible thing to do, particularly since you often need to know what the index is anyway.

However, to avoid inherited properties showing up when looping through the properties of any object, you can use the hasOwnProperty function:

for (var prop in someObject){
   if (someObject.hasOwnProperty(prop) {
         console.log(someObject[prop]);
   }
}
Jacob Mattison
  • 50,258
  • 9
  • 107
  • 126
0

You also have Ext.each which can be sometime useful.

Ext.each(myArray, console.log);
Drasill
  • 3,917
  • 29
  • 30