Reputation: 44
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.
Upvotes: 0
Views: 4959
Reputation: 612
When you modify Class directly, like here
tempClass.timei+1;
tempClass.id=i;
You are modifying the existing class instance.
Because you add this already existing instance in array with
arrayTemp.push(tempClass);
It means you edit the class you created in the beginning with
let tempClass ={} as ABC;
What you actually want to do, is create a new class instance for each iteration, like so
addToArray(){
let arrayTemp : ABC[]= [];
for (let i = 0; i < 4; i++) {
// create new instance of class for each iteration
let tempClass = new ABC();
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
}
}
Edit:
Don't forget to create your class with new
keyword! If you do intialization directly as let tempClass ={} as ABC;
you wont get actual representation of a class, you only get empty object that only looks like a ABC class to typescript.
Upvotes: 5