1

I have a small problem trying to code a snake game in js.

I have this function:

function move() {

    var aux = [];
    aux = snake.position[snake.position.length - 1];
    console.log(aux);

    if (snake.direction == 'r') {
        snake.position[snake.position.length - 1][1] += 1;
    };

    console.log(aux);
    //updateSnake();
    snake.position[snake.position.length - 2] = aux;
    updatePosition(snake.position);
};

The problem is that aux is changing itself without me doing anything to it, as you can see. The value from the first console.log is different from the second one! It's not like I'm changing its prototype.

Can you guys help me?

  • 2
    Isn't aux just snake.position[someindex] that you do change? – Zackline Mar 18 '17 at 12:36
  • Well, yeah! But the thing is. The first time I log that aux, it prints me [10,12] - The value of snake.position[2]. After that if, the value of aux changes to [10,13]. But I don't change that aux anywhere. Only the snake.position[2] changes.Aux shouldn't – Cosmin Serboteiu Mar 18 '17 at 12:39
  • Please, create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – sergdenisov Mar 18 '17 at 12:42
  • 2
    `aux` is just a reference to `snake.position[snake.position.length - 1]`, not a copy of the array: http://stackoverflow.com/q/6612385 – Korikulum Mar 18 '17 at 12:46
  • 1
    `aux = snake.position[snake.position.length - 1]` doesn't create a new array, it's just create a reference to the `snake.position[snake.position.length - 1]` array. – Titus Mar 18 '17 at 12:47
  • Thanks a lot guys! That helped a lot! – Cosmin Serboteiu Mar 18 '17 at 12:53

1 Answers1

0
if (snake.direction == 'r') {
    snake.position[snake.position.length - 1][1] += 1;
}

The above line is what changes the array aux. The first console.log() returns [10,12] as stated in the above comments. After that, the if statement is incrementing snake.position[snake.position.length - 1][1], which is the value of the variable. When calling console.log() for the second time, the variable aux is evaluated as [10,12+1], equivalent to [10,13], which is the expected result.

Wais Kamal
  • 5,858
  • 2
  • 17
  • 36