Ad

Javascript Is Setting Var To Early

- 1 answer

I am learning since some days JavaScript but now I have the problem that I want to set a var always after a calculation to the Old value like this:

var Old = [0,0];
var New = [0,0];

test();

function test() {
  Old = New;
  New[0] = 0;
  New[1] = 5;

  alert(Old + " : " + New);

  do_some_calculation_stuff();
}

but i dont understand why the Old and New value is always instantly the same and how to solve this problem.

Ad

Answer

Because assigning an array like that means just assigning the reference. If you want to make a shallow copy of what is in New, you need to do something like:

Old = New.slice(0);

The above is essentially a short form for doing this:

Old = [];
for (var i = 0; i < New.length; ++i) {
    Old[i] = New[i]
}
Ad
source: stackoverflow.com
Ad