array sort changing curent and old variable

后端 未结 3 1744
无人及你
无人及你 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.

    0 讨论(0)
  • 2021-01-24 18:53

    When you say

    var c2=c1;
    

    you are actually making c2 point to the same object referred by c1. And then you are changing the c1 Array object. Since c2 and c1 refer the same object, c1 and c2 will print the same.

    You need to make a copy of the Array object. You can use c1.slice() to do that, like this

    var c2 = c1.slice();
    

    Now c2 refers to a copy of the c1 array. So, changes made to the c1 will not affect the c2 object.

    0 讨论(0)
  • 2021-01-24 18:54

    Just use slice(0):

    var c1 = ["Saab", "Volvo", "BMW"];
    var c2=c1.slice(0);
    c1.sort();
    alert(c1);
    alert(c2);
    

    Here a sample:

    http://jsfiddle.net/c3161930/

    Best regards, Felipe

    0 讨论(0)
提交回复
热议问题