eLwoodianer
eLwoodianer

Reputation: 674

Passing an array by reference isn't working

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]
    }
}

Upvotes: 1

Views: 792

Answers (2)

Xotic750
Xotic750

Reputation: 23482

As has been mentioned, javascript uses pass-by-value, you can modify the objects elements/properties but not replace the object itself. slice returns a new array to the object. You will have to something like this instead.

slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array.

function callMeMaybe(i, board, boardCopy) {
    if (board[i] == 1) {
        //boardCopy = board.slice(0);
        var length = board.length,
            j = 0;

        boardCopy.length = 0;
        while (j < length) {
            if (Object.prototype.hasOwnProperty.call(board, j)) {
                boardCopy[j] = board[j];
            }

            j += 1;
        }

        boardCopy[i] = 0;
        console.log(board);
        console.log(boardCopy);
    }
}

Upvotes: 2

Raekye
Raekye

Reputation: 5131

You're assigning a new value to the local variable. It works when you do the splicing in callMeAnytime because that gets assigned to the "master/original variable" (which is passed to callMeMaybe, so callMeMaybe doesn't reassign the local variable)

Edit: And as millimoose stated, you can't pass by reference in Javascript in the first place. If you give us more details on what you're trying to do, we can probably point you in the right direction.

Upvotes: 1

Related Questions