i have a function called in ngInit(), that fills an array with objects of a class with values generated in a for loop, using array.push().
However, once the for loop completes, all the array items are the last-added instance of the class.
Class def
class ABC{
time: number;
id: number;
}
Function def
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
}
}
Output of console.log(arrayTemp[val])
Output of console.log(arrayTemp) after the for loop
I'm not sure why this happens, any help would be appreciated.


let tempClass ={} as ABC;inside the for loop if you want a new instance of the class with each iteration of the for loop.