首页 > 解决方案 > 为什么改变一个属性(对象)也会在不同的单独声明的属性中发生变化?

问题描述

我有 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 不受对过滤要求所做的更改的影响?

标签: javascriptangularmutation

解决方案


好的,所以您声明myData.property1.countryDocument的对象是非原始/参考值。所以这意味着两者this.defaultRequirementsthis.filteredRequirements都指向字面上相同的数据。

如果您要使用原始值(例如: a string)执行此操作,您将得到一个副本;所以this.defaultRequirementsthis.filteredRequirements将是完全分开的,并且可以在彼此没有影响的情况下被操纵。

以您想要的方式复制/复制对象是完全可能的,并且已经有很多关于它的讨论,我不会复制;我建议你看看这个很好地涵盖了它。


推荐阅读