Javascript:具有相同值的对象数组的每个元素

Ben*_*_TW 3 javascript arrays oop

我创建了一个包含对象的2D数组,每个对象都有两个变量。

当我打印出这些对象时,我发现每个对象都具有相同的值。

如果更改其中一个对象,其他对象也将更改。

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

它只打印9 22。我不知道发生了什么。

即使我尝试过:

arr[1][2] = new test(2, 3);
Run Code Online (Sandbox Code Playgroud)

打印9 2 3。

如果有人帮助我,我将不胜感激。

:P

tev*_*dar 10

JavaScript不是Python,请使用this,它将起作用。

class test{
    constructor(x, y){
        this.x = x;
        this.y = y;
    }
    print(){
        console.log(this.x, this.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();
    }
}
Run Code Online (Sandbox Code Playgroud)

(您幸运/不幸地最终在Window.self各处使用,)

  • @Teemu,谢谢。这让我有些不安,因为它应该一直在抱怨访问“ undefined”字段。 (2认同)

Ful*_*Guy 5

的分配x,并yself在构造函数是你的问题,改变selfthis以指向类对象的当前实例。

class test{
    constructor(x, y){
        this.x = x;
        this.y = y;
    }
    print(){
        console.log(this.x, this.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();
    }
}
Run Code Online (Sandbox Code Playgroud)

从MDN 文档

Window.self只读属性返回窗口本身,作为WindowProxy。可以在窗口对象(即window.self)或独立对象(self)上使用点符号。

因此,在您的情况下,当您分配xyself.x,创建了的self.y两个新属性,self并不断在循环中覆盖它们,从而导致迭代的最后一个值(2,2)被分配给的xy属性。self