【发布时间】:2016-09-23 19:39:26
【问题描述】:
我在 javascript 上有这个课程:
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;
};
我正在使用这个函数,它使用slice() 将this.board 变量(它是一个数组)复制到tempBoard 变量
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;
};
问题是在调用makemove() 之后tempBoard 和this.board 变量都被修改了。
有没有什么方法可以在没有引用的情况下复制数组?
【问题讨论】:
-
所以你想要一个深拷贝?
.slice()只做浅拷贝。 -
var tempBoard = []; this.board.slice().forEach(function(b){tempBoard.push(b)});
-
@JoseHermosillaRodrigo:也不例外。
-
数组
this.board是什么类型的数据?
标签: javascript arrays