Map () and forEach() loops in Js

The same

  1. Loop through each item in the array
  2. Value (current traversal item), index (current traversal item index), array (original array)
  3. Anonymous function, arrow function this points to window
  4. Only groups can be traversed, not objects

different

  1. ForEach does not return a value, even if a return is written inside a function, which is undefined.

    When a map writes return, it returns a new array of the values of the return (without changing the original array)

forEach

ForEach ((value, index, arr) => {console.log(' value :',value, 'index ', index,' original array ', arr); // console.log(this); Window return value * 2}) console.log('forEach returns value is ', result1) // Different from return, return undefinedCopy the code

map

Result2 = arr2.map((value, index, arr) => {console.log(' value :',value, 'index ', index,' original array ', arr); // console.log(this); Window return Value * 2}) console.log('map returns value is ', result2) // Returns twice the value of the original arrayCopy the code

PS: Modify the original array for map and forEach

  1. Both map and forEach can pass value when traversing arrays that hold reference data types. Property name directly modifies data in the original array.

    let objArr = [{num: 1}, {num: 2}, {num: 3}] let newArr = objarr.foreach ((obj) => {delete obj. Num obj. Name = 'obj'}) console.log(objArr);Copy the code
  2. Both map and forEach can only modify the original array through arR [index] when traversing data of primitive types

     let objArr = [5, 6, 7]
     ​
     objArr.forEach((value, index, arr) => {
       arr[index] = 999
     })
     ​
     console.log(objArr);
    Copy the code