数组排序改变CURENT老变 [英] array sort changing curent and old variable
问题描述
JS来源:
var c1 = ["Saab", "Volvo", "BMW"];
var c2=c1;
c1.sort();
document.getElementById("demo").innerHTML = '1 -> '+c1+'<br>2 -> '+c2;
结果:
1 - >宝马,萨博,沃尔沃
2 - >宝马,萨博,沃尔沃
RESULT: 1 -> BMW,Saab,Volvo 2 -> BMW,Saab,Volvo
我需要:
1 - >宝马,萨博,沃尔沃
2 - >萨博,沃尔沃,宝马
I need to be: 1 -> BMW,Saab,Volvo 2 -> Saab,Volvo,BMW
推荐答案
行:
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();
.slice( )
方法返回数组的一部分的副本,或者,如果你不带参数调用它(或只是一个开始指数 0
),它复制整个阵列。所以,那么 C1
和 C2
变量将指向两个不同的数组,你可以排序或修改一个没有改变其他。
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.
这篇关于数组排序改变CURENT老变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!