最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Change the value of an array changes original array JavaScript - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 11

Yes. 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.

发布评论

评论列表(0)

  1. 暂无评论