问题描述
这是有问题的代码:
const array = [
1, 2, 3
]
array.map(item => {
item = item + 1
})
console.log(array)
我认为 map
方法中的 item
(第一个)参数是对数组中原始项目的引用,直接对其进行更改会改变内容第一个数组的那个...不是真的吗?
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
函数返回一个新数组,它不会更改原始数组.
map
function returns a new array, it does not change the original one.
item
是箭头功能 item =>{...}
.赋值 item = item + 1
不会更改原始元素,而是会更改 item
局部变量.
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.
如果您想更改元素, forEach
函数会更高效,因为它不会创建新的数组:
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;
});
这篇关于为什么这个映射函数不改变原始数组中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!