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(pare);
valueArray = labelArray;
valueArray[0] = '-1';
labelArray[0] = '-';
All help is appreciated.
UPDATE (2019): It's been several years since I first did this post, and ES6 is used pretty much universally. So, I wanted to e back and add that, instead of using the slice()
method remended in the accepted answer, you can instead use array destructing in the following to make a copy:
valueArray = [...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(pare);
valueArray = labelArray;
valueArray[0] = '-1';
labelArray[0] = '-';
All help is appreciated.
UPDATE (2019): It's been several years since I first did this post, and ES6 is used pretty much universally. So, I wanted to e back and add that, instead of using the slice()
method remended in the accepted answer, you can instead use array destructing in the following to make a copy:
valueArray = [...labelArray];
Share
Improve this question
edited Oct 14, 2019 at 16:30
OpensaurusRex
asked Jan 26, 2012 at 20:17
OpensaurusRexOpensaurusRex
8421 gold badge12 silver badges31 bronze badges
3 Answers
Reset to default 11Yes. Both valueArray
and labelArray
reference the same underlying array. To make a copy, use slice():
valueArray = labelArray.slice(0);
NOTE: Slice() only copies 1 level deep, which works fine for primitive arrays. If the array contains plex objects, use something like jQuery's clone(), credit @Jonathan.
Am I just creating a reference to the labelArray […] ?
Yes, exactly. valueArray
and labelArray
still identify the same object, which hasn't been copied.
valueArray
is just a reference to labelArray
.
What you want to do is clone the array. You can do this using jQuery.clone() or a similar cloning function.