javascript - 为什么 forEach 会改变另一个过滤后的数组

标签 javascript

var arr = [{a: "one", b: "two"}];
/* in real code I have actual filter condition, but the filtered result
share some common properties with value */
var res = {
  arr1: arr.filter(x => x),
  arr2: arr.filter(x => x)
};

res.arr1.forEach(x => x.a = "a");

console.log(arr); //should print [{a: "one", b: "two"}]
console.log(res.arr1); //should print [{a: "a", b: "two"}]
console.log(res.arr2); //should print [{a: "one", b: "two"}]

如果我更改对象 resarr1 数组中的值,那么为什么更改会应用到 arr2res 还有吗? filter 创建新数组,然后不应应用效果。

我做错了什么?

最佳答案

新数组中的每个元素都保留相同的对象引用,因此您需要克隆该对象。如果没有嵌套值,则可以使用 Object.assign连同 Array#map方法。对于更深层次的克隆,你需要使用一些其他的库或者需要实现你自己的自定义函数。

var arr = [{a: "one", b: "two"}];
/* in real code I have actual filter condition, but the filtered result
share some common properties with value */
var res = {
  arr1: arr.map(x => Object.assign({}, x)),
  arr2: arr.map(x => Object.assign({}, x))
};

res.arr1.forEach(x => x.a = "a");

console.log(arr); //should print [{a: "one", b: "two"}]
console.log(res.arr1); //should print [{a: "a", b: "two"}]
console.log(res.arr2); //should print [{a: "one", b: "two"}]


仅供引用: What is the most efficient way to deep clone an object in JavaScript?

关于javascript - 为什么 forEach 会改变另一个过滤后的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49608495/

相关文章:

javascript - 引用磁盘上的图像时 Cordova 中的短暂(500 毫秒?)延迟

javascript - 重复的 jQuery 标签

javascript - 需要垫片设置 - jquery.flot/jquery.flot.selection

javascript - 谷歌地图标记位置错误

javascript - 在 React 中,更新嵌套数组状态项的正确方法是什么

javascript - 可折叠的div,但从某一点定义在一个变量中

javascript - 带有 Bootstrap 主题的 Mottie 虚拟键盘

Javascript 子例程不运行

javascript - CKEditor "insertHtml"适用于 FF 但不适用于 IE8

javascript - 具有重叠数据点的 d3.js voronoi