admin管理员组

文章数量:1430924

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?

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?

Share Improve this question edited Feb 22, 2011 at 21:23 ppecher asked Feb 22, 2011 at 21:17 ppecherppecher 1,9884 gold badges19 silver badges30 bronze badges 1
  • Shouldn't that be console.log(i) anyway? – Dutchie432 Commented Feb 22, 2011 at 21:22
Add a ment  | 

4 Answers 4

Reset to default 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./2011/01/04/exploring-javascript-for-in-loops/

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

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]);
   }
}

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

Ext.each(myArray, console.log);

本文标签: javascriptHow to make the enhanced for loop only look at actual array contentsStack Overflow