Sunday 15 May 2011

javascript - Passing an array by reference isn't working -


I am trying to pass a variable from context, but it is not working like this (or I hope It will be).

BoardCopy is still empty after callMeMaybe and I do not know why if I first code in the first code in the boardCopy Copying with = board.slice (0) and doing it in another function, it is working, but this is not an option, because the actual board will be very large and CallMeAnytime A recursive function will be more complex.

  callMeAnytime (3, [], [1, 0, 1, 1]); Function callMy other (index, move, board) {for (var i = index; i> = 0; i--) {var boardcopy = []; Call memebe (I, board, board copy) console.log (board); // [1, 1, 1, 1] console.log (boardcopy); // []}} Function call memebe (i, board, board copy) {if (board [i] == 1) {boardCopy = board.slice (0); Board copy [i] = 0; Console.log (board); // [1, 1, 1, 1] console.log (boardcopy); // [1, 1, 1, 0]}}    

as mentioned Javascript uses pass-by-value, you can modify the object elements / properties but can not replace the object, gives a new array for the object, instead you have to do something like this.

The slice does not change the original array, but gives a new "one-level deep" copy that contains copies of the elements cut from the original array. / P>

  Function call memebe (i, board, board copy) {if (board [i] == 1) {// boardCopy = board.slice (0); Var Length = Board. Lamb, J = 0; BoardCopyline = 0; While (J & lt; length) {if (object. Prototype HACOPhipty call (board, j)) {boardcopy [j] = board [j]; } J + = 1; } BoardCopy [i] = 0; Console.log (board); Console.log (boardCopy); }}    

No comments:

Post a Comment