I have been working with a JavaScript class:
function Node(board,x,y,t){
this.board = board;
this.x = x;
this.y = y;
this.playerTile = t;
this.oponentTile = getOponentTile(this.playerTile);
this.parent = null;
this.getChildren = getChildren;
};
In my code, there is a function where I copy the content of this.board
array into a new variable called tempBoard
using slice()
var getChildren = function() {
if(this.x==-1 && this.y ==-1){
var moves = getAllValidMoves(this.board,this.playerTile);
}
else{
var tempBoard = this.board.slice();
makeMove(tempBoard,this.playerTile,this.x,this.y);
var moves = getAllValidMoves(tempBoard,this.playerTile);
}
var children = [];
for(var i = 0;i<moves.length;i++){
var currentMove = moves[i];
var currentBoard = this.board.slice();
if(this.x==-1 && this.y ==-1){
children.push(new Node(currentBoard,currentMove[0],currentMove[1],this.playerTile));
}
else{
makeMove(currentBoard,this.playerTile,this.x,this.y)
children.push(new Node(currentBoard,currentMove[0],currentMove[1],this.oponentTile));
}
}
return children;
};
The issue arises when makemove()
is invoked, both tempBoard
and this.board
are being altered.
Is there a way to duplicate an array without affecting the original one?