更改数组的值更改原始数组 JavaScript

问题描述:

以下代码导致 id 0 中的两个元素都设置为 -,即使我只想将一个元素设置为 -1>.我只是创建了对 labelArray 的引用,还是其他什么?

The following code causes both elements from id 0 to be set to -, even though I want only one to be set to -1. Am I just creating a reference to the labelArray, or is something else?

labelArray.sort(compare);
valueArray = labelArray;
valueArray[0] = '-1';
labelArray[0] = '-';

感谢所有帮助.

更新(2019 年):自从我第一次写这篇文章已经好几年了,ES6 的使用非常普遍.所以,我想回来补充一点,而不是使用接受的答案中推荐的 slice() 方法,您可以改用 数组析构 在下面进行复制:

UPDATE (2019): It's been several years since I first did this post, and ES6 is used pretty much universally. So, I wanted to come back and add that, instead of using the slice() method recommended in the accepted answer, you can instead use array destructing in the following to make a copy:

valueArray = [...labelArray];

是的.valueArraylabelArray 引用相同的底层数组. 要制作副本,请使用 slice():

Yes. Both valueArray and labelArray reference the same underlying array. To make a copy, use slice():

valueArray = labelArray.slice(0);

注意:Slice() 仅复制 1 级深度,这适用于原始数组.如果数组包含复杂对象,请使用类似 jQuery 的 clone() 之类的东西,感谢@Jonathan.

NOTE: Slice() only copies 1 level deep, which works fine for primitive arrays. If the array contains complex objects, use something like jQuery's clone(), credit @Jonathan.