我创建了一个包含对象的二维数组,每个对象都有两个变量。
当我打印出这些对象时,发现每个对象都具有相同的值。
如果我更改一个对象,其他对象也会改变。
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();
}
}
它只打印九个2。 我不知道发生了什么。
即使我尝试:
arr[1][2] = new test(2, 3);
它输出九个数字 2 3。
如果有人帮助我,我将感激不尽。
:P
self.x
变成this.x
,等等,除非这真的是一个Python问题。 - Mark