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"}]
如果我更改对象 res
的 arr1
数组中的值,那么为什么更改会应用到 arr2
和 res
还有吗? 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/