最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does this map function not mutate the values in the original array? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share asked Jan 9, 2018 at 11:00 john maccarthyjohn maccarthy 6,3633 gold badges14 silver badges16 bronze badges 1
  • If you want to mutate each item in an array, you would use 'forEach' and then call a mutating method on each element. When you do item = item+1, you're not mutating item regardless of if you call .map or .forEach, because you're just reassigning a local variable. – TKoL Commented Jan 9, 2018 at 11:04
Add a ment  | 

3 Answers 3

Reset to default 5

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

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

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

发布评论

评论列表(0)

  1. 暂无评论