array sort changing curent and old variable

后端 未结 3 1747
无人及你
无人及你 2021-01-24 18:15

JS Source:

var c1 = [\"Saab\", \"Volvo\", \"BMW\"];
var c2=c1;
c1.sort();
document.getElementById(\"demo\").innerHTML = \'1 -> \'+c1+\'
2 -> \'+c2
3条回答
  •  天涯浪人
    2021-01-24 18:48

    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.

提交回复
热议问题