Why is my array.push() not pushing the correct values?

Viewed 35

I am coding chess and trying to push a pseudo legal move into an array and before pushing I am logging it and it is correct and after pushing it is also correct but when I log the array it pushed the wrong thing.

if (this.colour == 'white') {
         this.moveOffsets.yOffset = -1 * tileSize;
      }
      else {
         this.moveOffsets.yOffset = 1 * tileSize;
      }
      pseudoLegalPos.length = 0;
      pseudoLegalPos.push(this.x, this.y + this.moveOffsets.yOffset);
      console.log(pseudoLegalPos);
      this.pseudoLegal.push(pseudoLegalPos);
      console.log(pseudoLegalPos);
}

Also when I log the array it ended up pushing a value that was supposed to be pushed later in the function.

1 Answers

Assuming that's in a loop, doing

pseudoLegalPos.length = 0;
pseudoLegalPos.push(...);
this.pseudoLegal.push(pseudoLegalPos);

will only push multiple copies of the same pseudoLegalPos array into this.pseudoLegal.

Chances are you want

const pos = [this.x, this.y + this.moveOffsets.yOffset];
this.pseudoLegal.push(pos);

instead for fresh new poses.

Related