I'm trying to pass a variable by reference, but it isn't working like it should (or I've hoped it would).
boardCopy is still empty after callMeMaybe has been called and I don't know why. If I copy the board already in the first function with boardCopy = board.slice(0) and don't do this in the second function it's working, but that isn't an option, because the real board will be much bigger and callMeAnytime will be a recursive function and much more complex.
callMeAnytime(3, [], [1, 0, 1, 1]);
function callMeAnytime(index, moves, board) {
for (var i = index; i >= 0; i--) {
var boardCopy = [];
callMeMaybe(i, board, boardCopy)
console.log(board); // [1, 1, 1, 1]
console.log(boardCopy); // []
}
}
function callMeMaybe(i, board, boardCopy) {
if (board[i] == 1) {
boardCopy = board.slice(0);
boardCopy[i] = 0;
console.log(board); // [1, 1, 1, 1]
console.log(boardCopy); // [1, 1, 1, 0]
}
}
boardCopy = ...replaces the value of the local variableboardCopywith the right hand side of the assignment. Why would you expect it to change anything in the calling function? Javascript doesn't even have pass-by-reference semantics.