我有一个在 ngInit() 中调用的函数,它使用在for 循环中生成的值的类对象填充数组,使用array.push()。
但是,一旦 for 循环完成,所有数组项都是该类的最后添加实例。
类定义
class ABC{
time: number;
id: number;
 }
Run Code Online (Sandbox Code Playgroud)
函数定义
addToArray(){
 let arrayTemp : ABC[]= [];
 let tempClass ={} as ABC;
 for (let i = 0; i < 4; i++) {
 
   tempClass.timei+1;
   tempClass.id=i;
    let val=i;
    arrayTemp.push(tempClass);
    console.log(arrayTemp[val]);   // here class objects displayed correctly
}
   console.log(arrayTemp);  // here all elements are just the last added class object
  
  }
 }
Run Code Online (Sandbox Code Playgroud)
的输出的console.log(arrayTemp [VAL])
for 循环后 console.log(arrayTemp) 的输出
我不确定为什么会发生这种情况,任何帮助将不胜感激。