简体   繁体   English

如何使增强的for循环仅查看实际的数组内容

[英]How to make the enhanced for loop only look at actual 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? 有没有办法只遍历数组内容?

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... 抱歉,据我所知,这是遍历数组的正确方法。

Your loop is catching the methods and properties of Array.prototype in addition to the array's contents. 除了数组的内容,循环还捕获了Array.prototype的方法和属性。 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 : 就像JCOC611所说的那样,通常最好以“正确”的方式遍历数组,但是如果您不想这样做,则可以使用数组的hasOwnProperty函数来检查属性是否确实在数组中或是否在数组中。 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? 有关更多详细信息,请参见此问题: 为什么在数组迭代中使用“ for ... in”是个坏主意?

Also, this blog post has lots of information: http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/ 此外,此博客文章还包含很多信息: http : //javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/

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. 对于数组,将老式的for循环与索引一起使用可能是明智的选择,尤其是因为您经常需要知道索引到底是什么。

However, to avoid inherited properties showing up when looping through the properties of any object, you can use the hasOwnProperty function: 但是,为避免在遍历任何对象的属性时显示继承的属性,可以使用hasOwnProperty函数:

for (var prop in someObject){
   if (someObject.hasOwnProperty(prop) {
         console.log(someObject[prop]);
   }
}

您还可以使用Ext.each,它有时会很有用。

Ext.each(myArray, console.log);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM