js - some understanding of the forEach() function

insert image description here

1. Definition and usage

definition:

forEach()method is called for each element of the array and passes the element to the callback function. Note: forEach()The callback function will not be executed for an empty array.

usage:

// 箭头函数
forEach((element) => {
    
     /* … */ })
forEach((element, index) => {
    
     /* … */ })
forEach((element, index, array) => {
    
     /* … */ })

// 回调函数
forEach(callbackFn)
forEach(callbackFn, thisArg)

// 内联回调函数
forEach(function(element) {
    
     /* … */ })
forEach(function(element, index) {
    
     /* … */ })
forEach(function(element, index, array){
    
     /* … */ })
forEach(function(element, index, array) {
    
     /* … */ }, thisArg)

2. Will forEach change the original array?

结论: For simple data types, the original array will not be changed, but for complex data types, the direct assignment operation can change the original array;

1. Simple data types will not change the original array

      const arrNumber = [1, 2, 3, 4];
      arrNumber.forEach((item,index)=>{
    
    
        item = item*2
      })
      console.log("arrNumber:",arrNumber); // [1, 2, 3, 4]
  const arrString = ['Eula','Kaya','Umbar']
      arrString.forEach((item,index)=>{
    
    
        item = item+'_'+index
      })
      console.log("arrString:",arrString);// ['Eula','Kaya','Umbar']

Then if I just want to change the original array, I can write like this:

   const arrNumber = [1, 2, 3, 4];
   arrNumber.forEach((item,index,arr)=>{
    
    
        if(item % 2 === 0){
    
    
          console.log("可以被2整除的需要重新赋值:",item);
          arr[index] = 100/
        }
      })
      console.log("arrNumber:",arrNumber);//[1, 100, 3, 100]

Direct arr[index]; it is equivalent to your usual array name[item number] = value. In this way, the original array can be modified naturally;

2. The direct assignment of the reference data type can change the original array

const list = [
        {
    
     name: "Kaya", age: 18 },
        {
    
     name: "Eula", age: 19 },
        {
    
     name: "Umbar", age: 20 }
      ];

      // 直接进行赋值是可以改变原数组的 改变姓名
      list.forEach((item, index) => {
    
    
        if (item.name === "Eula") {
    
    
          item.name = "Xinjie";
        }
      });

      // 改变年龄
      list.forEach((item, index) => {
    
    
        item.age++;
      });

      console.log("list:", list);
      打印如下:
      0:{
    
    name: 'Kaya', age: 19}
	  1: {
    
    name: 'Xinjie', age: 20}
	  2: {
    
    name: 'Umbar', age: 21}

forEach()It is equivalent to copying the original array and operating on the copied data, because the basic type of data is equivalent to a deep copy, and the reference data is a shallow copy, which is equivalent to only copying the pointer address, and changing the data will also change the original array. Lose;

For primitive data types: number,string,Boolean,null,undefinedthey store variables and values ​​directly in stack memory.
The real data of the Object object is saved in the heap memory, and only the variables of the object and the corresponding heap address are saved in the stack, so operating the Object is actually directly operating the original array object itself.

3. Except for throwing an exception, there is no way to abort or jump out of the loop

When forEach traverses the array, you cannot use breakor returnand other keywords to jump out of the loop. Using it returncan only skip this loop, which is equivalent to continue.

1. Use return to jump out of this loop

  	  var arr = [1, 2, 3, 4, 5];
      arr.forEach(function (item) {
    
    
        // 只能跳出本次循环
        if (item === 3) {
    
    
          return;
        }
        console.log("item:",item); // 1 2  4 5
      });

2. Throw an error and jump out to terminate the entire loop (not recommended)

var arr = [1, 2, 3, 4, 5];
      try {
    
    
        arr.forEach(function (item) {
    
    
          // 只能跳出本次循环
          if (item === 3) {
    
    
            throw new Error("主动跳出循环");
          }
          console.log("item:", item); // 1 2 
        });
      } catch (error) {
    
    
        console.log("error:", error);
      }

注意: Throwing an exception can jump out of the entire loop body, but try catcha function is required to catch this exception, otherwise the console error will block the downward execution of the code;

3. forEach()方法It does not support the use of break or continue statements to break out of the loop or skip an item.

If you need to break out of the loop or skip an item, you should use for循环or other break或continuemethods that support statements.

4. Cannot handle asynchronous functions (async await)

1. First look at the following case:

async function test() {
    
    
    let arr = [3, 2, 1]
    arr.forEach(async item => {
    
    
        const res = await mockSync(item)
        console.log(res)
    })
    console.log('end')
}

function mockSync(x) {
    
    
    return new Promise((resolve, reject) => {
    
    
        setTimeout(() => {
    
    
                resolve(x)
        }, 1000 * x)
    })
}
test()
我们期望的结果是:
3
2 
1
end
但是实际上会输出:
end
1
2
3

2. There are two solutions to the above problem:

第一种: use normal for循环syntax

 function mockSync(x) {
    
    
        return new Promise((resolve, reject) => {
    
    
          setTimeout(() => {
    
    
            resolve(x);
          }, 1000 * x);
        });
      }
      // 使用for循环
      async function test(){
    
    
        let arr = [3, 2, 1];
        for(let i=0;i<arr.length;i++){
    
    
          const res = await mockSync(arr[i]);
          console.log(res);
        }
      }
      test();// 3,2,1

Now the execution sequence is normal: print 3 after waiting for 3 seconds, then print 2 after waiting for 2 seconds, and finally print 1 after waiting for 1 second;

第二种: use for of 循环to handle async functions

   function mockSync(x) {
    
    
        return new Promise((resolve, reject) => {
    
    
          setTimeout(() => {
    
    
            resolve(x);
          }, 1000 * x);
        });
      }
      // 使用for of 循环
      async function test() {
    
    
        let arr = [3, 2, 1];
        for (const item of arr) {
    
    
          const res = await mockSync(item);
          console.log("res:",res);
        }
      }
      test();

おすすめ

転載: blog.csdn.net/qq_43886365/article/details/131788576