I created a 2D array that contains an object, and each object has two variables.
When I printed out those objects, I found that every object has the same value.
If I change one of the objects, other objects will change too.
class test{
constructor(x, y){
self.x = x;
self.y = y;
}
print(){
console.log(self.x, self.y);
}
}
arr = new Array(3);
for(let i=0;i<3;i++){
arr[i] = new Array(3);
}
for(let i=0;i<3;i++){
for(let j=0;j<3;j++){
arr[i][j] = new test(i, j);
}
}
for(let i=0;i<3;i++){
for(let j=0;j<3;j++){
arr[i][j].print();
}
}
It just prints nine 2 2. I have no idea what's going on.
Even if I tried:
arr[1][2] = new test(2, 3);
It prints nine 2 3.
I will be appreciated if anyone helps me.
:P