The difference and connection between map and forEach

The difference and connection between map and forEach

1. The same points:

1. 都是循环遍历数组中的每一项

2. 每次执行匿名函数都支持三个参数,参数分别为item(当前每一项),index(索引值),arr(原数组)

3. 匿名函数中的this都是指向window

4. 只能遍历数组

2. Differences:

1. map()会分配内存空间存储新数组并返回,forEach()不会返回数据。

2. forEach()允许callback更改原始数组的元素。map()返回新的数组。

3. Usage scenario:

1. forEach适合于你并不打算改变数据的时候。

2. map()适用于你要改变数据值的时候。不仅仅在于它更快,而且返回一个新的数组。这样的优点在于你可以使用复合(composition)(map(), filter(), reduce()等组合使用)。

expand

1. foreach()

There is no return value!
使用方法:
    arr[].forEach(function(value,index,array){
            xxxxx
    })
  • Parameters: the current item in the value array, index the index of the current item, the original array of array;

  • There are several items in the array, so the anonymous callback function passed in needs to be executed several times;

  • In theory, this method has no return value, just traverses each item in the array, and does not modify the original array, but you can modify the original array by yourself through the index of the array.

      举个例子:
      var array = [1,3,5,9,7];  
      var res = array.forEach(function (item,index,input) {  
          input[index] = item*10;  
      })  
      console.log(res);//--> undefined;  
      console.log(array);//--> 通过数组索引改变了原数组; [10,30,50,90,70]
    

2. map()

If there is a return value, you can return it!
使用方法:
    arr[].map(function(value,index,array){
        xxx
        return xxx
    });
  • Parameters: the current item in the value array, the index of the current item at index, the original array of array;
  • Difference: The callback function of map supports the return return value. What is returned is equivalent to changing this item in the array to what (it does not affect the original array, but it is equivalent to cloning the original array, and the clone The corresponding item in the array of this copy has changed);

for example:

var array = [1,3,5,7,9];  
var res = array.map(function (item,index,input) {  
    return item*10;   
})  
console.log(res);//[10, 30, 50, 70, 90]
console.log(array);// [1, 3, 5, 7, 9] 不变

Guess you like

Origin blog.csdn.net/TC_DESpipi/article/details/128625829