为什么在 JavaScript 中更改数组会影响数组的副本? [英] Why does changing an Array in JavaScript affect copies of the array?

查看:32
本文介绍了为什么在 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 执行一个操作,然后提醒 myArraycopyOfMyArray.不知何故,当我对 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 执行一个操作,然后提醒 myNumbercopyOfMyNumber.在这里,我得到了预期的行为:myNumbercopyOfMyNumber 的不同值.

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.

您可以使用 slice [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.

这篇关于为什么在 JavaScript 中更改数组会影响数组的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆