Home  >  Article  >  Web Front-end  >  Comparing 4 Ways to Iterate Arrays in JavaScript

Comparing 4 Ways to Iterate Arrays in JavaScript

王林
王林Original
2023-09-04 08:25:02671browse

比较 JavaScript 中迭代数组的 4 种方法

If you already know the basics of JavaScript arrays, it's time to take your skills to the next level with more advanced topics. In this series of tutorials, you'll explore the intermediate topic of programming with arrays in JavaScript.

In almost every project involving arrays, we have to perform operations such as iterating or looping over arrays. There are many reasons why you might need to loop over an array, such as displaying array data as output or converting it.

You can iterate over arrays in JavaScript using many methods. In this tutorial, we'll take a look at all of them while discussing the pros or cons of each in detail.

method advantage shortcoming
for loop You can use break to exit early, suitable for asynchronous code, supported by general browsers Long and error-prone
forEach()Method Concise and easy to read No asynchronous support, no early exit break
for...ofLoop Use with other iterable types to allow early exit and syntax to reduce errors Less support for older browsers
for...inLoop Efficient on sparse arrays, allowing early exit Unexpected inherited elements may be returned
method Flow control with interrupt and resume? Can I use asynchronous code? Browser support Comments
for loop yes yes All browsers More detailed syntax, one-to-one errors
forEach()Method

No

No Modern Browser Concise and chained after other functions (i.e. map)
for...ofLoop

Yes

yes Modern Browser Simple syntax reduces errors
for...inLoop yes yes All browsers Valid for sparse arrays, unexpected (inherited) elements can be returned

Basic knowledge of accessing array elements

Let's start with the basics of accessing array elements using indexes. Array indexing in JavaScript starts from 0. This means that the first element can be accessed by using array_name[0] in the code. Likewise, for an array containing n elements, you can use array_name[n - 1] to access the last element.

let animals = ["Fox", "Dog", "Lion", "Cat", "Zebra"];

let first = animals[0];

let last = animals[4];

console.log(first);
// Outputs: Fox

console.log(last);
// Outputs: Zebra

Use for loop to iterate

One of the most common ways to loop through an array is the for loop. for The loop initializes the iteration variable to 0 to start the loop from the first element. Since we want to iterate over the entire array, we need to calculate the length of the array, which can be easily done using the length property. The last element in the array can then be accessed using array_name[length - 1].

The following code snippet shows us how to loop through an array using the for loop sequence:

let animals = ["Fox", "Dog", "Lion", "Cat", "Zebra"];

let animal_count = animals.length;

for(let i = 0; i < animal_count; i++) {
  console.log(animals[i]);
}
/* Outputs:
Fox
Dog
Lion
Cat
Zebra
*/

Note how we use the less than operator () instead of the less than or equal operator (<code>) as the loop end condition.

Using a for loop when looping over an array has two advantages: it is widely supported, and it allows you to control the flow of the loop through the break and continue statements. Once you find what you're looking for, you can exit the loop. for loops also work well when you're dealing with asynchronous code.

The disadvantage is that it is a bit verbose and you may make some minor mistakes occasionally.

Use the forEach() method to iterate

You can also iterate over arrays in JavaScript using the built-in forEach() method. This method accepts as its argument a callback function that is executed once for each array element. The callback function can be defined elsewhere, it can be an inline function or an arrow function.

The callback function can accept three different parameters:

  1. The current element itself
  2. The index of the current element
  3. We call the forEach() array of methods
let animals = ["Fox", "Dog", "Lion", "Cat", "Zebra"];

animals.forEach(animal => console.log(animal));
/* Outputs:
Fox
Dog
Lion
Cat
Zebra
*/

As you can see, using the forEach() method makes our code cleaner. Here is another example of using the second parameter of a callback function.

let animals = ["Fox", "Dog", "Lion", "Cat", "Zebra"];

animals.forEach((animal, idx) => {
  console.log(`Animal ${idx + 1}: ${animal}`);
});
/* Outputs:
Animal 1: Fox
Animal 2: Dog
Animal 3: Lion
Animal 4: Cat
Animal 5: Zebra
*/

Using forEach() is very suitable for simple iteration of arrays. However, you cannot use break and continue to exit a loop midway and change the program flow. Another disadvantage of using forEach() is that you cannot use asynchronous code with this method.

Use for...of loop to iterate

The ES6 standard adds a lot of new features to JavaScript. One of them is the concept of iterators and iterable objects. You can use a for...of loop to iterate over the values ​​in any object that implements the @@iterator method. Built-in types (such as Array, String, Set, or Map) can iterate over their values ​​using a for...of loop.

let animals = ["Fox", "Dog", "Lion", "Cat", "Zebra"];

for(let animal of animals) {
  console.log(animal);
}
/* Outputs:
Fox
Dog
Lion
Cat
Zebra
*/

There are many advantages to iterating using the for...of construct. For example, you can also use it to iterate over other built-in iterable types. Among other things, it allows you to break out of loops and control program flow using the break or continue statements.

The only potential drawback is slightly less browser support, but that all depends on your target audience.

Use for...in loop to iterate

You can also use the for...in statement to loop through the array. This will loop through all enumerable string properties of the object. This also includes inherited enumerable properties.

I would like to mention here that it is not recommended to use the for...in statement to iterate through a loop. This is because, as I mentioned before, this statement will iterate over all integer and non-integer properties, even if they are inherited. When we iterate over an array, we are usually only interested in integer keys.

for...in The traversal order of the loop is well defined and it starts with the traversal of non-negative integer keys. Non-negative integer keys are traversed in ascending order of value. Then iterate over the other string keys in the order they were created.

A sparse array is an array type that can be traversed better with a for...in loop than other methods. For example, a for...of loop will iterate over all empty slots in a sparse array, while a for...in loop will not.

Here is an example of using a for...in loop to iterate over a sparse array:

let words = new Array(10000);

words[0] = "pie";
words[548] = "language";
words[3497] = "hungry";

for(let idx in words) {
  if(Object.hasOwn(words, idx)) {
    console.log(`Position ${idx}: ${words[idx]}`);
  }
}
/* Outputs:
Position 0: pie
Position 548: language
Position 3497: hungry
*/

You may have noticed that we use a static method called Object.hasOwn() to check whether the specified property of the query object is indeed its own property.

Final Thoughts

You can always use a regular for loop to iterate over an array. It allows you to control program flow with the help of the break and Continue keywords, and also supports asynchronous code. On the other hand, it does require you to be careful about one mistake.

The

forEach() method provides a shorter way to loop through an array, but it is not suitable for asynchronous code. You also cannot use break and continue to break out of loops or control program flow.

for...of Loops give us the best of both worlds. We have full control over the program flow, and it works with asynchronous code as well. No need to worry about missing a beat.

Finally, for...in loops are not the recommended way to loop over arrays. However, it can be useful if the array you are looping over is very sparse.

The thumbnails for this article were generated using OpenAI’s DALL-E 2.

The above is the detailed content of Comparing 4 Ways to Iterate Arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn