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

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

问题描述:

我写了以下JavaScript:

I've written the following JavaScript:

var myArray = ['a', 'b', 'c'];
var copyOfMyArray = myArray;
copyOfMyArray.splice(0, 1);
alert(myArray); // alerts ['b','c']
alert(copyOfMyArray); // alerts ['b','c']

var myNumber = 5;
var copyOfMyNumber = myNumber;
copyOfMyNumber = copyOfMyNumber - 1;
alert(myNumber); // alerts 5
alert(copyOfMyNumber); // alerts 4        

此代码声明变量 myArray 并将其设置为数组值。然后它声明第二个变量 copyOfMyArray 并将其设置为 myArray
它在 copyOfMyArray 上执行操作,然后警告 myArray copyOfMyArray 。不知何故,当我在 copyOfMyArray 上执行操作时,似乎在 myArray 上执行相同的操作。

This code declares a variable myArray and sets it to an array value. It then declares a second variable copyOfMyArray and sets it to myArray. It performs an operation on copyOfMyArray and then alerts both myArray and copyOfMyArray. Somehow, when I perform an operation on copyOfMyArray, it appears that the same operation is performed on myArray.

然后代码使用数字值执行相同操作:它声明变量 myNumber 并将其设置为数字值。然后它声明第二个变量 copyOfMyNumber 并将其设置为 myNumber 。它对 copyOfMyNumber 执行操作,然后警告 myNumber copyOfMyNumber 。在这里,我得到了预期的行为: myNumber copyOfMyNumber 的不同值。

The code then does the same thing with a number value: It declares a variable myNumber and sets it to a number value. It then declares a second variable copyOfMyNumber and sets it to myNumber. It performs an operation on copyOfMyNumber and then alerts both myNumber and copyOfMyNumber. Here, I get the expected behavior: different values for myNumber and copyOfMyNumber.

数组和JavaScript中的数字有什么区别,它似乎更改数组会更改数组副本的值,其中更改数字不会更改数字副本的值?

What is the difference between an array and a number in JavaScript that it seems changing an array changes the value of a copy of the array, where as changing a number does not change the value of a copy of the number?

我猜测由于某种原因,数组是通过引用引用的,而数字是按值引用的,但为什么呢?我如何知道其他对象的行为?

I'm guessing that for some reason, the array is referred to by reference and the number by value, but why? How can I know what behavior to expect with other objects?

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.

您与数字示例的比较不正确顺便说一句。您为 copyOfMyNumber 分配了一个新值。如果您为 copyOfMyArray 指定一个新值,它将不会更改 myArray

Your comparison with the number example is not correct btw. You assign a new value to copyOfMyNumber. If you assign a new value to copyOfMyArray it will not change myArray either.

您可以使用 切片创建数组的副本 [docs]

var copyOfMyArray = myArray.slice(0);

但请注意,这只会返回一个副本,即数组不会被克隆。

But note that this only returns a shallow copy, i.e. objects inside the array will not be cloned.