The difference between vue forEach and map

Record the problems encountered in the work, select an item in the array on the right to delete, and the difference between forEach and map will come out.

Insert image description here

1. I wrote it using foreach at first, but the effect didn’t come out.

  this.rightTree:表示右边的数组
  this.oriFatherId.id:选中一个的id
   this.rightTree.forEach((i)=>{
           console.log(i.id);
          console.log(this.oriFatherId.id);
        if(i.id == this.oriFatherId.id){
         this.rightTree.splice(i.id,1)
        }
        // 然而发现每次删的都是第一个 就换了map

2. This uses map

 this.rightTree.splice(
        this.rightTree.map((a) => a.id).indexOf(this.oriFatherId.id),
        1
      );
      
      // 没问题了 

3. Then I printed the forEach and map

	//    console.log(this.rightTree.map((a) => a.id));
    //  this.rightTree.forEach((a) => {
    //   console.log(a.id);
   //  });

// Summarized
Insert image description here

4. The return value of forEach() is undefined and cannot be called in a chain. The values ​​in the array are printed out in a loop.

5.map() returns a new array, and the original array will not change.

Guess you like

Origin blog.csdn.net/weixin_53587375/article/details/123357802
Recommended