This article compares and summarizes four ways of traversing an array: for loop: for (let index=0; index < someArray.length; index++) { const elem = someArray[index]; // ··· } for-in loop: for (const key in someArray) { console.log(key); } Array method .forEach(): someArray.forEach((elem, index) => { console.log(elem, index); }); for-of loop: for (const elem of someArray) { console.log(elem); } for-of is usually the best choice. We'll see why. for loop [ES1]The for loop in JavaScript is very old, it has been around since ECMAScript 1. The for loop records 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?
for-in loop [ES1]The for-in loop is as old as the for loop, also existing in ECMAScript 1. The following code uses a for-in loop to output the key of arr: 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 over an array:
The actual purpose of for-in accessing inherited properties is to iterate over all enumerable properties of an object. Array Method .forEach() [ES5]Since neither for nor for-in are particularly suitable for looping over arrays, a helper method was 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 convenient: it allows us to access array elements and indices without having to perform a lot of operations. If we use arrow functions (introduced in ES6), the syntax will be more elegant. The main disadvantages of .forEach() are:
Abort .forEach() solutionIf you want to abort a loop like .forEach() , there is a workaround: .some() also loops over 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; // terminate the loop} console.log(elem); // This callback implicitly returns `undefined`, which // is a falsy value. And so the cycle continues. }); // Output: // 'red' // 'green' This can be said to be an abuse of .some(), and compared to for-of and break, it is not easy to understand this code. for-of loop [ES6]The for-of loop is supported in 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 at looping over arrays: Used to iterate over array elements. You can use await
You can even use break and continue with outer scopes. for-of and iterablesfor-of can not only traverse arrays, but also iterate over iterable 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' Iterating over myMap generates [key, value] pairs, each of which can be accessed directly by destructuring it. for-of and array indexingThe array method .entries() returns an iterable of [index, value] pairs. If you use for-of and destructuring with this method, you can easily access the array index: const arr = ['chocolate', 'vanilla', 'strawberry']; for (const [index, elem] of arr.entries()) { console.log(index, elem); } // Output: // 0, 'chocolate' // 1, 'vanilla' // 2, 'strawberry' SummarizeThe usability of the for-of loop is better than for, for-in, and .forEach(). Generally the performance differences between the four loop mechanisms should be insignificant. If you are doing something computationally intensive, it is better to switch to WebAssembly. This concludes this article on the four ways to loop through an array in JS. For more information about looping through an array in JS, please search for previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Detailed explanation of docker's high availability configuration
>>: MySQL sequence AUTO_INCREMENT detailed explanation and example code
Table of contents 2 solutions for file upload Bas...
The simple installation configuration of mysql5.7...
1. Grammar location [=|~|~*|^~|@] /uri/ { ... } 2...
Preface When we build a MySQL cluster, we natural...
1. Create tables <br /> First, create two t...
The sudo command allows a trusted user to run a p...
1. This is a bit complicated to understand, I hop...
As Web developers, although we are not profession...
Log rotation is a very common function on Linux s...
What? What star coat? Well, let’s look at the pic...
Recently, when I was learning Django, I needed to...
Table of contents Nesting Parent-child component ...
Table of contents 1. CDN introduction 1.1 react (...
1. Introduction MySQL is used in the project. I i...
In centos7, the permissions of the /etc/rc.d/rc.l...