Array.forEach() method

Preface

For JavaScript beginners, when it comes to traversing an array, we may first think of a for loop. In fact, there are many methods for traversing arrays in JavaScript. Today we will introduce a new method for traversing arrays-Array.forEach()

1. forEach() method

语法:array.forEach(callback(currentvalue,index,arr) ,thisValue)

Among them
callbackis the function executed by each element in the array. The function can accept 1-3 parameters:

  currentvalueThe parameter indicates the current element item of the array, the required parameter
  index parameter indicates the current element index, the optional parameter
  arrparameter indicates the array to which the current element belongs, and the optional parameter

thisValueRepresents the this point when the callback function callback() is executed. Optional parameters. When not writing, the default is to point to the window global

Example

    var arr = [1, 3, 5, 13, 2];
    var res = arr.forEach(function(item,index) {
    
    
        console.log(`数组第${
      
      index+1}个元素是${
      
      item}`);
    })
    console.log(res);//forEach的返回值为undefined,

Running result:
Insert picture description here
knock on the blackboard-forEach() has no return value!

2. The difference between forEach() and for loop

  • forEach() method cannot end early

For example, we end the loop when we want to find an element that meets the condition.
In the for statement we can write

    var arr = [1, 3, 5, 13, 2];
    for (var i = 0; i < arr.length; i++) {
    
    
            if (arr[i] == 3) {
    
    
                console.log("找到了3,并结束循环");
                break;
            }
            console.log(arr[i]);
        }

The for statement was executed twice, and the 3 in the array was found the second time, and the loop ended.
operation result:
Insert picture description here

What about forEach()?

    var arr = [1, 3, 5, 13, 2];
    arr.forEach(function(item) {
    
    
            if (item == 3) {
    
    
                return console.log('找到了3,但未结束遍历');
            }
            console.log(item);
        })

operation result:
Insert picture description here

I wanted to end the traversal with return after finding 3, but the results still output the elements after 3.

Terminate or jump out of the forEach() loop, unless an exception is thrown, so if you want to execute whether an array meets a certain condition and then returns a certain value, you can use a general for loop to achieve, or use Array.every() or Array.some();

Array.every () array for detecting whether all elements of all meet the specified conditions

Array.some() is used to detect whether any of the elements in the array meets the specified conditions

  • forEach() will skip null values

        var arr1 = [1, 3, , 13, 2];
        var arr2 = [1, 3, , 13, 2];
        for (var i = 0; i < arr1.length; i++) {
    
    
            arr1[i] = 2;
        }
        console.log(arr1);
        var newarr = [];
        arr2.forEach(function(item, index) {
    
    
            // item = 2; //修改不了原数组            
            arr2[index] = 2;
        })
        console.log(arr2);

Operation result:
Insert picture description here
We can find that the for loop modifies the null value in the array, and the forEach() method skips the null value.
But it should be noted that we can use the forEach() method to modify the array elements and cannot use item to modify directly. The item is equivalent to the value copied from arr2 and does not actually point to the elements in the original array arr2. So we want to modify each element of the original array to modify it by getting its index value index:arr2[index] = 2;

  • The number of loops of forEach() is determined by the initial length of the array

    var arr1 = [1, 3, , 13, 2];
        var arr2 = [1, 3, , 13, 2];

        for (var i = 0; i < arr1.length; i++) {
    
    
            if (arr1[i] == 3) {
    
    
                arr1.push(14);
                arr1.push(5);
            }
            console.log("数组循环了" + (i + 1) + "次");
        }
        console.log(arr1);

        var newarr = [];
        arr2.forEach(function(item, index) {
    
    
            if (arr2[index] == 3) {
    
    
                arr2.push(14);
                arr2.push(5);
            }
            console.log("数组循环了" + index + "次");
        })
        console.log(arr2);

Operation result:
Insert picture description here
We can find that when the for loop is adding data to the array, the number of loops also increases. The forEach() method only loops the initial length of the array arr2.

  • forEach is suitable for only traversing collections or arrays, while for is more efficient in more complex loops

Guess you like

Origin blog.csdn.net/qq_35370002/article/details/107913331