Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 当我更改对象数组中的一个值时,为什么所有值都会更改?打字稿_Arrays_Loops_Typescript_For Loop - Fatal编程技术网

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”而不声明其值/格式吗?