简体   繁体   English

为什么这个映射函数不改变原始数组中的值?

[英]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方法中的item (第一个)参数是对数组中原始项目的引用,并且直接对其进行更改会更改该第一个数组的内容……不是吗?

map function returns a new array, it does not change the original one. map函数返回一个新数组,它不会更改原始数组。

item is a local variable here in arrow function item => {...} . item是这里的局部变量,在箭头函数 item => {...} The assignment item = item + 1 does not change the original element, it rather changes item local variable. 分配item = item + 1不会更改原始元素,而是会更改item局部变量。

If you'd like to change the elements forEach function is more efficient because it does not create a new array: 如果您想更改元素,那么forEach函数会更有效,因为它不会创建新的数组:

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; Mozilla说;

The map() method creates a new array with the results of calling a provided function on every element in the calling array. map()方法创建一个新数组,并在调用数组中的每个元素上调用提供的函数。

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

So, map function doesn't mutate values of the array. 因此,map函数不会使数组的值发生变化。

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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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