JS Source:
var c1 = [\"Saab\", \"Volvo\", \"BMW\"];
var c2=c1;
c1.sort();
document.getElementById(\"demo\").innerHTML = \'1 -> \'+c1+\'
2 -> \'+c2
The line:
var c2=c1;
...doesn't create a copy of the array, it creates a second reference to the same underlying array object. So modifications that you make via either variable will affect the same array, whether that be sorting, adding elements, or whatever.
Fortunately it's easy to create a copy of an array:
var c2 = c1.slice();
The .slice() method returns a copy of a portion of an array, or, if you call it with no arguments (or with just a start index of 0
) it copies the whole array. So then the c1
and c2
variables will refer to two different arrays and you can sort or otherwise modify one without changing the other.