Why does this map function not mutate the values in the original array?

流过昼夜 提交于 2021-02-05 08:00:54

问题


Here is the code in question:

const array = [
  1, 2, 3
]

array.map(item => {
  item = item + 1
})

console.log(array)

I thought that the item (first) argument in the map method is a reference to the original item in the array, and that mutating it directly would change the contents of that first array... is that not true?


回答1:


map function returns a new array, it does not change the original one.

item is a local variable here in arrow function item => {...}. The assignment item = item + 1 does not change the original element, it rather changes item local variable.

If you'd like to change the elements forEach function is more efficient because it does not create a new array:

array.forEach((item, index) => {
    array[index] = item + 1;
});



回答2:


Your array contains primitives type elements (integer here). Variables of type primitive cannot be mutated by its reference. Mutating is possible if for example elements of your array are objects, like below:

var array = [{val: 1}, {val: 2}, {val: 3}];
array.map(item => {item.val = item.val + 1});
console.log(array);



回答3:


Mozilla says;

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

So, map function doesn't mutate values of the array.

I know you don't want to this, but you can use this:

const array = [
  1, 2, 3
]

array.map((item, k) => {
  array[k] = item + 1
})

console.log(array)


来源:https://stackoverflow.com/questions/48166706/why-does-this-map-function-not-mutate-the-values-in-the-original-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!