Arrays 当我更改对象数组中的一个值时,为什么所有值都会更改?打字稿
对Arrays 当我更改对象数组中的一个值时,为什么所有值都会更改?打字稿,arrays,loops,typescript,for-loop,Arrays,Loops,Typescript,For Loop,对 sortDates(){ let index = 0; for(let year of this.yearList){ let yearInfo = this.yearInfo; this.year.push(yearInfo) index++; } this.year[2].year = '123' 0:{year: "123", info:
sortDates(){
let index = 0;
for(let year of this.yearList){
let yearInfo = this.yearInfo;
this.year.push(yearInfo)
index++;
}
this.year[2].year = '123'
0:{year: "123", info: Array(12)}
1:{year: "123", info: Array(12)}
2:{year: "123", info: Array(12)}
第二个允许我更改“年”的值,而不更改所有元素的值。第一种方法将每个元素更改为相同的值
示例:如果2016年是for循环中的最后一个值,那么数组中的所有值都将是2016年的“年”
sortDates(){
let index = 0;
for(let year of this.yearList){
let yearInfo {
year: '',
info: [
{
date:'Dec',
total: 0
},
{
date:'Nov',
total: 0
},
{
date:'Oct',
total: 0
}
]
};
this.year.push(yearInfo)
index++;
}
对
sortDates(){
let index = 0;
for(let year of this.yearList){
let yearInfo = this.yearInfo;
this.year.push(yearInfo)
index++;
}
this.year[2].year = '123'
0:{year: "123", info: Array(12)}
1:{year: "123", info: Array(12)}
2:{year: "123", info: Array(12)}
有没有更好的方法获得第二个结果?为什么会出现第一个结果?谢谢
编辑:使用Object.assign help可能多次将同一实例添加到数组中,而不是不同的实例。我猜是因为您在“push”方法上分配了“this.yearInfo”的引用,从而在所有数组位置上引用了相同的变量。如果修改数组中的一项,则修改的是“this.yearInfo”。在另一种情况下,您正在通过执行“let yearInfo{…}”创建一个对象的新实例,数组上的每个位置都引用一个唯一的对象。请检查此代码段:并查看原始“数据”是如何修改的。@JuanStiza这完全有意义,并且与我的代码当前所做的相同,你知道我有什么方法可以使用“let yearinfo”而不声明其值/格式吗?