简体   繁体   中英

Standard JavaScript practice for iterating through an entire array?

Suppose I want to loop through an entire array to access each element. Is it standard practice amongst JavaScript developers to use a for loop, for...in loop, or for...of loop?

For example:

var myArray = ["apples", "oranges", "pears"];

For loop

for (var index = 0; index < myArray.length; index++)
    console.log(myArray[index]);

For...in loop

for (var index in myArray)
    console.log(myArray[index]);

For...of loop

for (var element of myArray)
    console.log(element);

forEach should be the way to go, as part of the Array.prototype functions.

For loop

 for (var index = 0; index < myArray.length; index++) console.log(myArray[index]) 

If I had to pick one of the above, vanilla for-loop with length above is the most preferred.

For...in loop

 for (var index in myArray) console.log(myArray[index]); 

You should avoid this at all cost! It's bad practice to mix idioms meant for Object with Array. You may run into buggy iterations through unwanted elements

For loop

for (var index = 0; index < myArray.length; index++)
console.log(myArray[index]);

This is the best choice for an array, and crossbrowser ! It will permit to break the loop when you want, but not with a Array.forEach

For in

Avoid this approach with array !

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