Summary of Four Ways of Loop Traversing Array in JS

  • 2021-10-24 18:49:20
  • OfStack

This article compares and summarizes four ways to traverse arrays:

for loop:


for (let index=0; index < someArray.length; index++) {
 const elem = someArray[index];
 //  Exactly 
}

for-in cycle:


for (const key in someArray) {
 console.log(key);
}

Array Method. forEach ():


someArray.forEach((elem, index) => {
 console.log(elem, index);
});

for-of cycle:


for (const elem of someArray) {
 console.log(elem);
}

for-of is usually the best choice. We'll understand why.

for Loop [ES1]

The for loop in JavaScript is very old, and it already exists in ECMAScript 1. for loops the index and value of each element of arr:


const arr = ['a', 'b', 'c'];
arr.prop = 'property value';

for (let index=0; index < arr.length; index++) {
 const elem = arr[index];
 console.log(index, elem);
}

// Output:
// 0, 'a'
// 1, 'b'
// 2, 'c'

What are the advantages and disadvantages of the for loop?

It is versatile, but it is also troublesome when we want to traverse arrays. If we don't want to loop from the first array element, it is still useful, but it is difficult to do this with other loop mechanisms.

for-in Cycle [ES1]

for-in cycle is as old as for cycle 1, and also exists in ECMAScript 1. The following code outputs key of arr in an for-in loop:


const arr = ['a', 'b', 'c'];
arr.prop = 'property value';

for (const key in arr) {
 console.log(key);
}

// Output:
// '0'
// '1'
// '2'
// 'prop'

for-in is not a good way to loop through arrays:

It accesses attribute keys, not values. As attribute keys, the index of array elements is a string, not a number. It accesses all enumerable attribute keys (own and inherited), not just those of Array elements.

for-in The practical use of accessing inherited properties is to traverse all enumerable properties of an object.

Array Method. forEach () [ES5]

Since neither for nor for-in is particularly suitable for looping over arrays, a helper method is introduced in ECMAScript 5: Array. prototype. forEach ():


const arr = ['a', 'b', 'c'];
arr.prop = 'property value';

arr.forEach((elem, index) => {
 console.log(elem, index);
});

// Output:
// 'a', 0
// 'b', 1
// 'c', 2

This approach is really handy: It gives us access to array elements and indexes without having to do a lot of work. If you use the arrow function (introduced in ES6), it will be more elegant in syntax.

The main disadvantages of. forEach () are:

You cannot use await in its loop body. You cannot exit the. forEach () loop early. break can be used in the for loop.

Solution to abort. forEach ()

If you want to abort loops such as. forEach (), there is a solution:. some () also loops through all array elements and stops when its callback returns a true value.


const arr = ['red', 'green', 'blue'];
arr.some((elem, index) => {
 if (index >= 2) {
 return true; //  Abort loop 
 }
 console.log(elem);
 // This callback implicitly returns  `undefined` , this 
 // Yes 1 False values.   Therefore, the cycle continues. 
});

// Output:
// 'red'
// 'green'

It can be said that this is an abuse of. some (), which is not easy to understand compared with for-of and break.

for-of Cycle [ES6]

The for-of loop starts with support for ECMAScript 6:


const arr = ['a', 'b', 'c'];
arr.prop = 'property value';

for (const elem of arr) {
 console.log(elem);
}
// Output:
// 'a'
// 'b'
// 'c'

for-of is very effective when iterating through arrays:

Used to traverse array elements.

You can use await

You can easily migrate to for-await-of if necessary.

You can even use break and continue for external scope.

for-of and Iterable Objects

for-of can traverse not only arrays, but also iterative objects, such as Map:


const myMap = new Map()
 .set(false, 'no')
 .set(true, 'yes')
;
for (const [key, value] of myMap) {
 console.log(key, value);
}

// Output:
// false, 'no'
// true, 'yes'

Traversing myMap generates [key, value] pairs, which can be deconstructed to directly access every 1 pairs of data.

for-of and Array Indexes

The array method. entries () returns 1 iterative [index, value] pair. If you use for-of and use this method for deconstruction, you can easily access the array index:


for (const key in someArray) {
 console.log(key);
}
0

Summarize

The availability of the for-of loop is better than that of for, for-in, and. forEach ().

Generally, the performance difference between the four loop mechanisms should be insignificant. If you want to do a lot of computation, it is better to switch to WebAssembly.


Related articles: