在javascript中更改数组会影响数组的副本,为什么?

在javascript中更改数组会影响数组的副本,为什么?

问题描述:

JavaScript中的数组也是一个对象,变量只保存对象的引用,而不是对象本身。因此,这两个变量都引用了同一个对象。

但是为什么?



我尝试了什么:



An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.
but why?

What I have tried:

var func= new function () {
         var A = [20, 30, 25, 5, 3, 2];
         var B = A;

         for (var i = 0; i <= A.length - 1; i++) {
             if (A[i] > A[i+1]) {
                 var tmp = A[i];
                 A[i] = A[i + 1];
                 A[i + 1] = tmp;
             }
         }

             var big = A[A.length-1];
             var index = 0;

             for (var j = 0; j <= B.length-1; j++) {
                 if (big == B[j])
                 {
                     index = j;
                     break;
                 }
             }
             console.log(A);
             console.log(B);
             return (index);
     };

简单:它是相同的数组。

Simple: it's the same array.
var A = [20, 30, 25, 5, 3, 2];
var B = A;



创建 A 并将其指向一个值数组,然后创建 B 并从 A 复制指针 >到 B ,因此它们都指向内存中的相同位置。因此,如果您通过 B $ c>来访问数据,那么通过 A 对数据进行的任何更改都将更改数据

要获取阵列数据的副本,请使用切片 [ ^ ]功能:


Creates A and "points" it at an array of values, then creates B and copies the "pointer" from A to B, so they both refer to the same locations in memory. Hence, any change to the data via A will also change the data if you access it via B
To get a copy of the array data, use the slice[^] function:

var A = [20, 30, 25, 5, 3, 2];
var B = A.slice();


因为语言有效。另一种方法是在分配时复制另一个对象,例如,

Because so the language works. The alternative would be to copy the other object on assignment, for example, after
var B = A;

B 将引用(引用的对象) A 的副本,这两个对象将是独立的(这是如何,例如 struct s表现为 C / C ++ 编程语言。)



请注意,这样的替代方案将是昂贵的,并且您可能总是通过明确地复制对象(在您的情况下是数组)获得相同的结果。

B would reference a copy of (the object referenced by) A and the two objects would have been independent (this is how, for instance structs behave in C/C++ programming languages).

Please note, such alternative would be 'expensive' and you may always obtain the same result by explicitely copying the object (in your case the array).