【发布时间】:2018-04-24 21:07:09
【问题描述】:
我正在尝试将数组元素的值分配给对象。在第一次尝试类似bar = foo[0]; 之后,我发现对bar 的任何更改也会更改foo[0],因为具有相同的引用。
太棒了,没人想到,在阅读了 immutability 和 ES6 Object.assign() 方法和 spread 属性后,我认为它会解决这个问题。但是,在这种情况下它不会。我错过了什么?
编辑:抱歉,accountTypes 混淆了,我修正了这个例子。
另外,我想保留 Settings 的类结构,所以 let copy = JSON.parse(JSON.stringify(original)); 在这种情况下并不是我真正想要的。
//this object will change according to a selection
currentPreset;
//this should remain unchanged
presets: {name: string, settings: Settings}[] = [];
ngOnInit()
{
this.currentPreset = {
name: '',
settings: new Settings()
}
this.presets.push({name: 'Preset1', settings: new Settings({
settingOne: 'foo',
settingTwo: false,
settingThree: 14
})
});
}
/**
* Select an item from the `presets` array and assign it,
* by value(not reference), to `currentPreset`.
*
* @Usage In an HTML form, a <select> element's `change` event calls
* this method to fill the form's controls with the values of a
* selected item from the `presets` array. Subsequent calls to this
* method should not affect the value of the `presets` array.
*
* @param value - Expects a numerical index or the string 'new'
*/
setPreset(value)
{
if(value == 'new')
{
this.currentPreset.name = '';
this.currentPreset.settings.reset();
}
else
{
this.currentPreset = {...this.presets[value]};
//same as above
//this.currentPreset = Object.assign({}, this.presets[value]);
}
}
【问题讨论】:
-
你能提供一个更完整或更好的例子吗?
accountTypes是什么?value是什么?什么是您不想被突变的值,突变之前是什么,突变之后是什么? -
使用这些操作符,您正在制作
Settings的卷影副本,在所有更新中都是相同的实例 -
使用对象扩展或
Object.assign只会创建一个浅拷贝。因此,该副本的变异属性仍将更改原始属性中的相同属性。您可能想尝试创建深层副本。 this question 的答案显示了一些这样做的方法。
标签: javascript typescript ecmascript-6