数组映射函数不会改变元素 [英] Array map function doesn't change elements
问题描述
在 JavaScript 中,我有一个数组,它是
In JavaScript, I have an array, which is
array = [true, false]
在某些情况下,我试图初始化这个数组
In some cases, I am trying to initialize this array
array.map(item => {
item = false
})
运行上述代码后,数组没有改变,仍然是[true, false]
,所以.map
有时不可靠吗?
After running the above code, the array is not changed, it is still [true, false]
, so is .map
not reliable sometimes?
还有一个问题:运行下面的代码后,数组发生了变化.为什么在这种情况下有效?
ONE MORE QUESTION: After running my below code, the array is changed. Why does it work in this case?
let array = [{id:1, checked: false}, {id:2, checked:true}]
array.map(item => {
item.checked = true
})
数组变成了[{id:1, checked: true}, {id:2, checked:true}]
推荐答案
JavaScript Array map() 方法
JavaScript Array map() Method
*) 使用为每个数组元素调用函数的结果创建一个新数组,并按顺序为数组中的每个元素调用一次提供的函数.
*)creates a new array with the results of calling a function for every array element and it calls the provided function once for each element in an array, in order.
注意:map()方法对没有值的数组元素不执行函数,也不会改变原数组.
Note: map() Method does not execute the function for array elements without values and it does not change the original array.
这篇关于数组映射函数不会改变元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!