简体   繁体   中英

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

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?

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;
});

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); 

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM