Javascript 尝试将更改作为一个整体保存为包含自定义对象的数组中的数组
我试图做一个if语句,如果数组板与2个更改前相同,它会警告我说undd非法播放。 但是,由于ifboardHistory.length>=3,每个数组在旋转3圈后都会变得相同{但它总是向我发出警告,而我看不出有任何理由向我发出警告,因为它总是在变化,并且永远不会变成相同的值 我做错了什么Javascript 尝试将更改作为一个整体保存为包含自定义对象的数组中的数组,javascript,arrays,Javascript,Arrays,我试图做一个if语句,如果数组板与2个更改前相同,它会警告我说undd非法播放。 但是,由于ifboardHistory.length>=3,每个数组在旋转3圈后都会变得相同{但它总是向我发出警告,而我看不出有任何理由向我发出警告,因为它总是在变化,并且永远不会变成相同的值 我做错了什么 var turn; var boardSize; var board; var boardHistory; var changer; function setup() { createCanvas(4
var turn;
var boardSize;
var board;
var boardHistory;
var changer;
function setup() {
createCanvas(400, 400);
boardSize = 8;
turn = false;
board = [];
boardHistory = [];
changer = 0;
for (var y = 0; y < boardSize; y++) {
for (var x = 0; x < boardSize; x++) {
board.push(new Piece(x, y, 0));
}
}
boardHistory.push(board);
}
function mouseClicked() {
for (var y = 0; y < boardSize; y++) {
for (var x = 0; x < boardSize; x++) {
board[y * boardSize + x].colour = changer;
}
}
var play = true;
if (boardHistory.length >= 3) {
if (board == boardHistory[(boardHistory.length - 3)]) {
play = false;
}
}
if (play) {
turn = !turn;
boardHistory.push(board);
console.log("played");
} else {
console.log("undid illegal play, " + (boardHistory.length - 3));
console.log(boardHistory[(boardHistory.length - 3)]);
}
console.log(board);
changer++;
}
function Piece(x, y, colour) {
this.x = x;
this.y = y;
this.colour = colour;
this.arrayNum = this.y * boardSize + this.x;
}
var转向;
板尺寸;
var板;
历史;
无功变换器;
功能设置{
CreateCanvas400400;
木板尺寸=8;
转向=假;
董事会=[];
董事会历史=[];
变换器=0;
forvar y=0;y我认为你面临的问题有两个不同的地方:
boardHistory.push(board);
及
即使您在mouseclicked函数中修改board的值,变量包含对象的引用,而不是对象的副本。因此,如果您在一个位置进行更改,您将在另一个位置看到它
我想用一个例子会更清楚:
var board = [1,2,3]
var boardHist = []
boardHist[0] = board; //This is similar of what you are doing
console.log(board == boardHist[0]); //Obviously we are getting true
board[0] = 5; //Now we change the first value of board
console.log(board == boardHist[0]); //This is still true
console.log(boardHist[0]); //We will get [5,2,3]
你能创建一个提琴或代码片段吗?因为在没有看到它的情况下很难跟踪发生了什么,但我如何制作它,这样它才能保存一个副本?我想我是如何制作的,已经制作了一个副本。有很多方法可以做到。你可以在这里查看它们:
var board = [1,2,3]
var boardHist = []
boardHist[0] = board; //This is similar of what you are doing
console.log(board == boardHist[0]); //Obviously we are getting true
board[0] = 5; //Now we change the first value of board
console.log(board == boardHist[0]); //This is still true
console.log(boardHist[0]); //We will get [5,2,3]