简体   繁体   English

我应该使用for循环结构还是forEach方法进行迭代?

[英]Should I be using the for-loop construct or the forEach method for iteration?

Is one way more efficient? 一种方式更有效吗? Are there any limitations in one method versus the other? 一种方法与另一种方法有任何限制吗? Thanks for any input you guys can give me ;-) 感谢你们给我的任何意见;-)

The Array.prototype.forEach method is part of the ECMAScript 5th Edition Specification, is available on all browsers but not in IE. Array.prototype.forEach方法是ECMAScript第5版规范的一部分,可在所有浏览器上使用,但不能在IE中使用。

I would suggest you to use a simple sequential for loop, IMO is more efficient since forEach needs a callback function, a function will be created starting a closure and you don't need to care about IE. 我建议你使用一个简单的顺序for循环,IMO更有效,因为forEach需要一个回调函数,一个函数将被创建启动一个闭包,你不需要关心IE。

But if you want to use forEach and all the other new Array.prototype methods such as map , filter , every , some , etc... you can add an implementation for IE, in the pages I linked. 但是如果你想使用forEach和所有其他新的Array.prototype方法,比如mapfiltereverysome等等......你可以在我链接的页面中添加IE的实现。

Similar to for each but supported in all browsers 类似于每个但在所有浏览器中都支持

for (var i = 0, myArrayElement; myArrayElement = myArray[i]; i++) { 
   //now you can just use 
  // myArrayElement
  // instead of 
  // myArray[i]
}

Just to be aware, I use this when iterating though form collections (ie document.forms[0].elements) 要注意,我在迭代表单集合时使用它(即document.forms [0] .elements)

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

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