Should I use the for-loop construct or the forEach method to iterate?

Is one way more efficient? Are there any restrictions on one method compared to another? Thanks for any input you guys can give me; -)

+4
source share
2 answers

The Array.prototype.forEach method is part of the ECMAScript 5th Edition specification, available on all browsers , but not in IE.

I would suggest you use a simple sequential for loop, IMO is more efficient, since forEach needs a callback function, a function will start that starts closing, and you don’t have to worry 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 on the linked pages.

+7
source

Similar 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] } 

To keep up to date, I use this when repeating, although collections of forms (ie document.forms [0] .elements)

+2
source

Source: https://habr.com/ru/post/1312806/


All Articles