Changing the value of an array modifies the original JavaScript array

The following code forces both elements with identifier 0 set to - , although I want only one of them to be set to -1 . Am I just creating a link to a labelArray, or is it something else?

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

Any help is appreciated.

UPDATE (2019): It has been several years since I first wrote this post, and ES6 is used almost universally. So, I wanted to go back and add that instead of using the slice() method recommended in the accepted answer, you can instead use an array that destroys to create a copy:

 valueArray = [...labelArray]; 
+5
source share
3 answers

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

 valueArray = labelArray.slice(0); 

NOTE. Slice () only copies 1 level of depth, which is great for primitive arrays. If the array contains complex objects, use something like jQuery clone () , credit @Jonathan.

+10
source

Am I just creating a link to labelArray [& hellip;]?

Yes exactly. valueArray and labelArray still identify the same object that was not copied.

+2
source

valueArray is just a reference to labelArray .

What you want to do is clone an array. You can do this using jQuery.clone () or a similar clone function.

+1
source

Source: https://habr.com/ru/post/1393251/


All Articles