7 Ways to Master Array Traversal in JavaScript

As a JavaScript developer, it is very important to be familiar with array traversal and manipulation. Array traversal is one of the basic requirements for processing and manipulating array elements. This article will introduce 10 common array traversal methods in JavaScript to help you become an expert in array operations.

Array traversal for loop forEach method for…of loop map method reduce method for…in loop filter method

for loop

The or loop is one of the most basic and commonly used array traversal methods. It uses a counter variable to iterate over the array elements, usually of the form:

Copy Code
for (initialExpression; condition; incrementExpression) {
  statement;
}

Among them, initialExpression is an expression executed before the loop starts, usually used to initialize counter variables; condition is a test performed before each loop iteration, and the loop will continue only when the condition is true; incrementExpression is performed during each loop iteration An expression that is executed later, usually used to update counter variables.

For array traversal, we can use the counter variable of the for loop to access each element in the array, for example:

javascriptCopy Code
var array = [1, 2, 3, 4, 5];
for (var i = 0; i < array.length; i + + ) {
  console.log(array[i]);
}

The i here is the counter variable, the initial value is 0, and 1 is added after each loop until i is equal to the length of the array. Within the loop body, we can access each element via array index array[i].

forEach method

forEach is a function method of arrays in JavaScript that can execute a specified function on each element in the array. The forEach loop automatically iterates the array, executing the callback function for each element and skipping undefined elements in the array.

The syntax of the forEach method is as follows:

javascriptCopy Code
array.forEach(function(currentValue, index, array) {
  //Execution content
}, thisValue);

Among them, the first parameter is the callback function, which can accept three parameters: the currently processed element value currentValue, the currently processed element index index, and the currently operated array object array. The second parameter thisValue is optional, indicating that when executing the callback function, it will be used as the value of the this keyword in the function body.

For example, we can use the forEach method to iterate through the array and output each element:

javascriptCopy Code
var array = [1, 2, 3, 4, 5];
array.forEach(function(element) {
  console.log(element);
});

for…of loop

The for…of loop is a new loop syntax in ES6, which can be used to traverse iterable objects such as arrays, strings, Maps, and Sets. Different from the traditional for loop, the for…of loop statement itself does not contain initialization variables, loop conditions and iterators, but directly traverses each element in the iteration object.

The syntax of the for…of loop is as follows:

javascriptCopy Code
for (variable of iterable) {
  // Loop body
}

Among them, variable represents the variable that will be assigned to the next element in the iteration object in each iteration, and the iterable parameter is an iterable object, such as an array or a string. Within the loop body, we can use variables to access the currently traversed element.

For example, we can use a for…of loop to iterate through the array and output each element:

javascriptCopy Code
var array = [1, 2, 3, 4, 5];
for (var element of array) {
  console.log(element);
}

The element variable here will be assigned to each element in the array in turn, and then output to the console in the loop body.

It should be noted that the for…of loop can only be used to traverse iterable objects, not ordinary objects. If you need to traverse the properties of an object, you can use a for…in loop.

The callback function here has only one parameter element, which represents the currently processed element value, which will be passed to each element in the array in turn. After the loop ends, each element in the array will be traversed and output to the console.

It should be noted that the forEach method will automatically skip undefined elements in the array, so you don’t have to worry about holes in the array when using it.

map method

map() is a built-in function method of JavaScript arrays that performs a specified function on each element in the array and returns a new array. It does not modify the original array, but returns a new array whose elements are the return values of the callback function.

The map() method syntax is as follows:

javascriptCopy Code
array.map(function(currentValue, index, array) {
  //Execution content
}, thisValue);

The first parameter is the callback function, which can accept three parameters: the currently processed element value currentValue, the currently processed element index index, and the currently operated array object array. The second parameter thisValue is optional, indicating that when executing the callback function, it will be used as the value of the this keyword in the function body.

For example, we can use the map() method to iterate through the array and multiply each element by 2:

javascriptCopy Code
var numbers = [1, 2, 3, 4, 5];
var doubledNumbers = numbers.map(function(num) {
  return num * 2;
});
console.log(doubledNumbers); // [2, 4, 6, 8, 10]

The callback function here has only one parameter num, which represents the currently processed element value, which will be passed to each element in the array in turn. After the loop ends, the doubledNumbers array contains the result of multiplying each element in the original array by 2.

It should be noted that the map() method returns a new array rather than modifying the original array. It also does not modify the elements in the original array.

for…in loop

The for…in loop is a loop statement used in JavaScript to traverse the properties of an object. Similar to the traditional for loop statement, the for…in loop also needs to specify an iteration variable and an enumerable object. In each iteration, the iteration variable will be assigned the next property name of the enumerable object, and then we can use this property name to access the corresponding property value.

The syntax of the for…in loop is as follows:

javascriptCopy Code
for (variable in object) {
  // Loop body
}

Among them, variable means that in each iteration, it will be assigned the name of the next enumerable attribute in the object, and the object parameter is an ordinary object. Within the loop body, we can use variable variables to access the currently traversed attribute values.

For example, we can use a for…in loop to iterate through the object and output the name and value of each property:

javascriptCopy Code
var obj = {
  name: 'Tom',
  age: 18,
  gender: 'Male'
};
for (var prop in obj) {
  console.log(prop + ': ' + obj[prop]);
}

The prop variable here will be assigned to each attribute name in the object obj in turn, and then use obj[prop] in the loop body to access the corresponding attribute value. After the loop ends, all attribute names and attribute values will be output to the console.

It should be noted that the for…in loop will not only traverse the properties of the object itself, but also traverse the properties on the object’s prototype chain. Therefore, when using a for…in loop, you need to use the hasOwnProperty() method to determine whether the object has the property to avoid unnecessary property access.

filter method

filter() is a built-in function method of JavaScript arrays, used to filter elements in the array that meet specified conditions and return a new array. It does not modify the original array, but returns a new array containing elements that meet the filter criteria.

The syntax of the filter() method is as follows:

javascriptCopy Code
array.filter(function(currentValue, index, array) {
  // Specify conditional judgment
}, thisValue);

The first parameter is the callback function, which can accept three parameters: the currently processed element value currentValue, the currently processed element index index, and the currently operated array object array. The second parameter thisValue is optional, indicating that when executing the callback function, it will be used as the value of the this keyword in the function body.

For example, we can use the filter() method to filter out elements greater than or equal to 5 in the array:

javascriptCopy Code
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var filteredNumbers = numbers.filter(function(num) {
  return num >= 5;
});
console.log(filteredNumbers); // [5, 6, 7, 8, 9, 10]

The callback function here has only one parameter num, which represents the currently processed element value, which will be passed to each element in the array in turn. The judgment condition in the callback function return num >= 5 means that only when the element is greater than or equal to 5, true will be returned and it will be retained in the new array.

It should be noted that the filter() method returns a new array rather than modifying the original array. It also does not modify the elements in the original array. If there are no elements that satisfy the condition, the new array returned will be an empty array.

reduce method

reduce() is a built-in function method of JavaScript arrays, which is used to accumulate elements in the array and reduce the array to a single value. It implements the accumulation operation through the provided callback function and returns the final result.

The syntax of the reduce() method is as follows:

javascriptCopy Code
array.reduce(function(accumulator, currentValue, index, array) {
  // Accumulation operation
}, initialValue);

The first parameter is the callback function, which can accept four parameters: accumulator (accumulator), currently processed element value (currentValue), currently processed element index (index) and currently operating array object (array). The second parameter initialValue is optional and represents the initial cumulative value.

For example, we can use the reduce() method to sum the elements in an array:

javascriptCopy Code
var numbers = [1, 2, 3, 4, 5];
var sum = numbers.reduce(function(total, num) {
  return total + num;
}, 0);
console.log(sum); // 15

The callback function here accepts two parameters, total and num. Total represents the cumulative value, with an initial value of 0, and num represents the currently processed element value. In each iteration, the callback function adds total to the current element value num and returns the new cumulative value. Ultimately, the reduce() method returns the accumulated value after the last iteration.

It should be noted that if no initial value (initialValue) is provided, the first element of the array will be used as the initial cumulative value, and iteration will start from the second element of the array. If the array is empty and no initial value is provided, a TypeError exception will be thrown.

In addition, the reduce() method also has some advanced uses. For example, it can be used to implement operations such as the maximum value, minimum value, and average of an array. By writing corresponding logic in the callback function, the accumulation operation on the array can be flexibly performed.

Complete project attachment: Click here to download