javascript - 为什么改变一个属性(对象)也会在不同的单独声明的属性中发生变化?
问题描述
我有 2 个这样声明的属性:
ngOnInit() {
this.defaultRequirements = myData.property1.countryDocument; //should never change
this.filteredRequirements = myData.property1.countryDocument;
}
当我运行这个 onFilter 函数时,defaultRequirements 属性也会发生变化。
onFilter(selectedSections) {
let index = -1;
this.defaultRequirements.forEach(country => {
index++;
const filteredSectionsList = [];
country.section.forEach(section => {
selectedSections.value.forEach(selectedSelection => {
const selection = selectedSelection.split(/\s*[-]\s*/);
if (country.countryCode === selection[0]) {
console.log('matched');
filteredSectionsList.push(section);
}
});
const countryObj = Object.assign({}, country, {
section: [...filteredSectionsList]
})
// Here is the issue, when filtering, this.defaultRequirements also gets changed!
this.filteredRequirements[index] = countryObj;
})
})
}
问题
我不明白如何改变 this.filteredRequirements 也改变 this.defaultRequirements (它们都等于同一件事)!如何避免这种行为并使 defaultRequirements 不受对过滤要求所做的更改的影响?
解决方案
好的,所以您声明myData.property1.countryDocument
的对象是非原始/参考值。所以这意味着两者this.defaultRequirements
和this.filteredRequirements
都指向字面上相同的数据。
如果您要使用原始值(例如: a string
)执行此操作,您将得到一个副本;所以this.defaultRequirements
和this.filteredRequirements
将是完全分开的,并且可以在彼此没有影响的情况下被操纵。
以您想要的方式复制/复制对象是完全可能的,并且已经有很多关于它的讨论,我不会复制;我建议你看看这个很好地涵盖了它。
推荐阅读
- javascript - 如何将子数组与json对象分开
- aws-api-gateway - 发生 CloudWatch 警报时以电子邮件形式发送失败的 JSON 请求
- linux - 如何使用 Windows Management Instrumentation (WMI) 将 Linux 上的 ansible 连接到 Windows 服务器
- c++ - OpenCV 从指针内存泄漏中恢复 Mat
- oauth - 如何确保在日历 api 的 oauth 屏幕中默认选中或取消选中权限?
- c++ - 如何更改结构中主函数中的变量?
- javascript - 如何避免在使用 FileReader 时发生 NotReadable
- pandas - 根据另一个数据框填充值
- reactjs - 如何使正交相机居中
- git - git 尝试克隆最后一个点的 repo 时出错