Array map compared to forEach

During the interview, the interviewer asked me what is the difference between the array methods Map and forEach?

Map returns a new array, forEach does not.

The interviewer smiled. “What else?”

“No?”

Interviewer: “Do they change the array?”

Me: “No”

“Sure?”

“HMM…”

“Go home and wait for notice.”

Then meng force, not satisfied, try a wave.

  1. An array of plain primitive types
let arr = [1, 2, 3 , 4] let arrmap = arr.map(item => { item = item+1 return item }) console.log(arr) console.log(arrmap) let arrEach = Arr. ForEach (item => {item = item+1 return item}) console.log(arr) console.log(arrEach) 2, 3, 4] // console.log(arrmap) [2, 3, 4, 5] // console.log(arr) [1, 2, 3, 4] // console.log(arrEach) undefinedCopy the code

The assignment to item by both methods does not change the original array.

  1. Array of reference types modify assignment directly
let arr3 = [ {value:1}, {value:2}, {value:3}, {value:4}, ] let arr3map = arr3.map(item => { item = { name: 'change' } return item }) console.log(arr3) console.log(arr3map) let arr3Each = arr3.forEach(item => { item = { name: 'change'} return item}) console.log(arr3) console.log(arr3Each) // output // console.log(arr3) [{"value": 1},{"value": 2},{ "value": 3},{"value": 4}] // console.log(arr3map) [{name: 'change'},{name: 'change'},{name: 'change'},{name: 'change'}] // console.log(arr3) [{"value": 1},{"value": 2},{ "value": 3},{"value": 4}] // console.log(arr3Each) undefinedCopy the code

The forEach and map methods do not modify the original array.

  1. Reference type array to modify subproperties
let arr2 = [ {value:1}, {value:2}, {value:3}, {value:4}, ] let arr2map = arr2.map(item => {item.value = item.value+1 return item}) console.log(arr2) console.log(arr2map) // output  // console.log(arr2) [{"value": 2},{"value": 3},{"value": 4},{"value": 5}] // console.log(arr2map) [{"value": 2},{"value": 3},{"value": 4},{"value": 5}]Copy the code

The map method modifies the array. Is that what the interviewer is talking about?

let arr2 = [ {value:1}, {value:2}, {value:3}, {value:4}, ] let arr2Each = arr2.forEach(item => { item.value = item.value+1 return item }) console.log(arr2) console.log(arr2Each) / / / / the console output. The log (arr2) [{" value ": 2}, {" value" : 3}, {" value ": 4}, {5}" value ":] / / the console log (arr2Each) is undefinedCopy the code

The forEach method also changes the original array

conclusion

Therefore, the values in map and forEach are shallow copies. The effect of map and forEach on the original array is the same under the same operation. There is no such thing as map not changing the original array while forEach changes the original array.