JS's for loop, forin loop, forof loop, foreach loop, map loop, and reduce() loop method are the most practical and detailed explanations.

Table of contents

for loop

for in loop

for loop

for each

map loop

reduce method


for loop

A for loop is a commonly used programming statement used to repeatedly execute a block of code until a certain condition is met. The for loop is usually used to traverse arrays, file lists, etc. The syntax is as follows:

for 变量名 in 列表
do
    循环体
done

Among them, the variable name represents the loop variable, the list can be a set of strings, file names, command output, etc., and the loop body is the code block that needs to be executed repeatedly. In each loop, the variable name will take the values ​​in the list in turn until all the values ​​in the list have been traversed.

The execution process of the for loop is as follows:

  1. Take the first element from the sequence and assign it to a variable;
  2. Execute the code block;
  3. Point the variable to the next element in the sequence, and go back to step 2 to continue;
  4. When there are no more elements in the sequence, exit the loop.

In a for loop, you can use the break statement to end the loop early, or you can use the continue statement to skip the current iteration and go directly to the next iteration.

array = ['李青','盖伦','卡特琳娜','约里克','金克斯','拉克丝'];
for (let i = 0; i < array.length; i++) {
  //console.log(i)//它输出了 0, 1, 2, 3, 4, 5输出是他们的下标
  console.log(array[i])//输出的是array的值;
}

for in loop

for...inA loop is a looping construct in JavaScript for traversing object properties. Its syntax is as follows:

var obj= {瞎子:李青,草丛伦:盖伦,不祥之刃:卡特琳娜,掘墓:约里克,非主流:金克斯,光辉:拉克丝};
for (var key in obj) {
  console.log(key + ': ' + obj[key]);
}

In this example we have an object with three properties obj. Through for...inthe loop, we traverse objthe attributes of and print the name and corresponding value of each attribute.

Here are for...insome important features and considerations of loops:

  1. Loop order: for...inLoops are not guaranteed to traverse object properties in a particular order. The order in which properties are traversed may vary by JavaScript engine implementation and may have different results in different environments.

  2. Traversing object properties: for...inThe loop traverses the object's own enumerable properties and inherited enumerable properties. If you only want to traverse the properties of the object itself, you can use Object.hasOwnProperty()the method to filter.

  3. Iterating over arrays: While for...inloops can be used to iterate over arrays, it is not recommended. Because it iterates over the indices (property names) of the array, not the elements of the array. A more suitable way to iterate over an array is to use for...ofthe loop or Array.forEach()method.

  4. Iteration order: for...inThe traversal order of the loop is uncertain, so the business logic processing should not depend on the traversal order of the attributes.

  5. Iterate over enumerable properties: for...inThe loop will only iterate over the enumerable properties of the object. If a property is set to be non-enumerable (via Object.defineProperty()or similar), then it will not be for...inlooped over.

In summary, for...ina loop is an iterative structure for traversing object properties. It can be used to iterate over enumerable properties of objects, but is not optimal when iterating over arrays. When using for...inloops, it should be noted that the order of attribute traversal is indeterminate, and attention should be paid to filtering inherited attributes and non-enumerable attributes.

for loop

for...ofA loop is a loop structure used in JavaScript to traverse iterable objects (such as arrays, strings, sets, maps, etc.). Its syntax is as follows:

var array = ['李青', '盖伦', '卡特琳娜', '约里克', '金克斯', '拉克丝'];

for (var element of array) {
  console.log(element);//输出结果 李青,盖伦,卡特琳娜,约里克,金克斯,拉克丝
}

In the above example, we created an arrayarray called containing some hero names. Then, for...ofloop through each element in the array using and console.log()print each element to the console via the function.

Please note that for...ofwhen looping through the array, each element will be fetched in sequence according to the order of the array, and the code in the loop body will be executed.

for each

forEachmethod, which is a built-in method of the array object, is used to traverse the array and perform the specified operation on each element.

The following is forEacha detailed description and example of the method:

grammar:

array.forEach(function(currentValue, index, array) {
  // 执行操作的代码
}, thisArg);

Parameter Description:

  • function(currentValue, index, array): Required. Indicates the function to be performed on each element. It can receive three parameters:
    • currentValue: The value of the element currently being processed.
    • index(optional): The index of the element currently being processed.
    • array(optional): forEachArray object to call the method on.
  • thisArg(optional): The value passed to the function as thisthe value of the .

Example:

var array = ['李青', '盖伦', '卡特琳娜', '约里克', '金克斯', '拉克丝'];

array.forEach(function(element, index) {
  console.log('索引 ' + index + ': ' + element);//渲染结果:
//索引 0: 李青,索引 1: 盖伦,索引 2: 卡特琳娜,索引 3: 约里克,索引 4: 金克斯,索引 5: 拉克丝
});

In the above example, we used forEachthe method to iterate over arrayeach element in the array . During the traversal process, we define an anonymous function that receives two parameters elementand index, which represent the value and index of the current element respectively. Then, we use the function in the body of the loop console.log()to print the value and index of each element.

Note that the method processes each element in turn in the order of the array and cannot use or forEachin loops . If you need to break the loop or skip certain elements during the traversal, consider using a loop or other control flow statement.breakcontinuefor...of

map loop

overview

The map method, one of the higher-order functions provided by JavaScript arrays, takes a function as an argument and executes that function on each element in the array. In this way, developers can easily transform array elements or generate new arrays without writing explicit loops.
usage

The key to using the map method is understanding the function passed to it. This function is often called a mapping function, and it defines an operation or transformation for each element in the array. The map function accepts three arguments: the element currently being processed, the index of the current element, and the original array to operate on.
The specific steps to use the map method are as follows:

1.定义映射函数,可使用匿名函数或命名函数。
2.调用数组的 map 方法,将映射函数作为参数传入。

For example, we want to double every element in the array, we can define the following mapping function:

function double(element) {
  return element * 2;
}

We can then apply the mapping function to the array using the map method:

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(double);

In this small example, the map method will call the mapping function double for each element in the numbers array, and form a new array doubledNumbers with the return value.
return value characteristics

The return value of the map method is unique in that it returns a brand new array without changing the original array. This means that the original array remains unchanged, and the resulting new array contains the elements processed by the mapping function. Therefore, the map method is a pure function and does not modify the original data.

Also, since the map method returns a new array, we can chain calls to other array methods such as filter, reduce, etc. to further process the data. Combining and chaining calls of this method can improve the readability and maintainability of the code.

It should be noted that the map method will only traverse the existing array elements, and will not execute deleted or unassigned items. If the elements in the array are modified or deleted, the result of the map method will be affected when the mapping function is executed.

reduce() method
overview

The reduce method is a higher-order function for JavaScript arrays that aggregates all elements of the array into a single result. It uses an accumulator and a callback function to perform aggregation operations.
usage

The basic syntax of the reduce method is as follows:

array.reduce(callback, initialValue)

Among them, array is the array to be operated; callback is the callback function for the aggregation operation; initialValue is an optional initial value, which is used as the initial value of the accumulator when the callback function is called for the first time.

The callback function callback accepts four parameters: accumulator (accumulator), currentValue (current value), currentIndex (current index) and array (original array). The callback function will be applied to each element of the array in turn, performing aggregation operations from left to right.
The following example demonstrates the use of the reduce method:

    Compute the sum of array elements:

const arr = [1, 2, 3, 4, 5];

const sum = arr.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);

console.log(sum); // 输出:15

In the above example, we defined an array called arr and used the reduce method to calculate the sum of all elements of the array. The callback function function(accumulator, currentValue) adds the accumulator to the current value currentValue and returns the new accumulator value.

    Find the largest value in an array:

const arr = [7, 2, 9, 1, 5];

const max = arr.reduce(function(accumulator, currentValue) {
  return Math.max(accumulator, currentValue);
}, arr[0]);

console.log(max); // 输出:9

In this example, we define an array called arr and use the reduce method to find the maximum value in the array. The callback function function(accumulator, currentValue) compares the accumulator accumulator with the current value currentValue using the Math.max function, and returns the larger value as the new accumulator value. The value of the initial accumulator is set to arr[0], the first element of the array.

    Array element counting and sorting:

const arr = ['apple', 'banana', 'apple', 'orange', 'banana'];

const result = arr.reduce(function(accumulator, currentValue) {
  if (!accumulator[currentValue]) {
    accumulator[currentValue] = 1;
  } else {
    accumulator[currentValue]++;
  }
  return accumulator;
}, {});

console.log(result);
// 输出:
// {
//   apple: 2,
//   banana: 2,
//   orange: 1
// }

We define an array called arr, and use the reduce method to count the occurrences of each element, and store the result in an object. The callback function function(accumulator, currentValue) judges whether the count of the current value currentValue exists in the accumulator, if not, initialize it to 1, otherwise increase the count. The value of the initial accumulator via {} creates an empty object.
Precautions

    The reduce method can accept an optional initialValue, which is used as the initial value of the accumulator when the callback function is called for the first time. If no initial value is provided, the initial value of the accumulator will be the first element of the array the first time the callback function is called.
    The reduce method returns the final result of the aggregation, not an array.

Finally, how do we choose these methods?
Let's introduce:

The choice of which loop to use depends on your specific needs and data structure. The following is a brief description and applicable scenarios for each rotation method:

  1. for loop:

    • The for loop is the most basic loop structure, which traverses the array or performs repeated operations by specifying the start condition, termination condition and operation of each iteration of the loop.
    • Useful when you need precise control over loop counts and indexing, and for simple traversal or manipulation of arrays.
  2. for-in loop:

    • The for-in loop is used to traverse the enumerable properties of an object, including its own properties and inherited properties.
    • Suitable for iterating over object properties, but not recommended for iterating over arrays, as it iterates over array indices and extra properties.
  3. for-of loop:

    • The for-of loop is used to iterate over the elements of an iterable object (such as an array, string, Set, Map, etc.).
    • It is suitable for situations where you need to iterate over the elements of an object, which provides a concise syntax and better performance.
  4. forEach loop:

    • The forEach loop is a built-in method of arrays that iterates through each element of the array and executes a callback function for each element.
    • It is suitable for traversing and manipulating arrays, but cannot use break or return to interrupt the loop.
  5. map loop:

    • The map loop is a built-in method of the array, which is used to traverse each element of the array and return a new array, and the elements of the new array are the return values ​​of the callback function.
    • It is suitable for traversing and transforming arrays, and returns a new array.
  6. reduce() loop:

    • reduce() is a built-in method of an array, which is used to perform cumulative calculations on the elements of the array and return the final result.
    • It is suitable for situations where aggregation calculations need to be performed on array elements, such as summing, averaging, etc.

According to different requirements, choosing an appropriate loop method can improve the readability and performance of the code. For simple traversal operations, for loops, for-of loops, and forEach loops are all good choices. If you need to transform the array during traversal, you can use a map loop. And for cases where cumulative calculations need to be performed on array elements, the reduce() loop is a useful tool.

It should be noted that when using any loop method, the efficiency and performance of the loop must be considered, and time-consuming operations or deep nested loops should be avoided in the loop body.

Guess you like

Origin blog.csdn.net/wangxuanyang_zer/article/details/131844304