简体   繁体   中英

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.

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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