全局变量的值发生了变化,javascript

Joe*_*ito 0 javascript variables jquery

我有这个代码片段,我不知道为什么变量的值发生了变化.

while (increment > 0) {
        for (i = increment; i < n; i++) {
            var unsorted = list;
            console.log(unsorted + " -> unsorted" + i);
            var temp = list[i];
            var j = i;
            while (j >= increment && list[j - increment] > temp) {
                list[j] = list[j - increment];
                j -= increment;
            }
            list[j] = temp;
            console.log(unsorted + " -> must not change" + i);
            console.log(list + "-> must not be the same below");
        }
 }
Run Code Online (Sandbox Code Playgroud)

当我unsorted再次记录变量时,值已更改?为什么?

SLa*_*aks 5

你只有一个阵列.

var unsorted = list创建指向同一个数组实例的第二个引用.

相反,您可以调用list.slice(),返回数组的(浅)副本.