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
4 Answers
Reset to default 2Your 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
版权声明:本文标题:javascript - How to make the enhanced for loop only look at actual array contents - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745555798a2663176.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论