Change the value of an array changes original array JavaScript

前端 未结 3 729
面向向阳花
面向向阳花 2020-11-29 13:41

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 re

相关标签:
3条回答
  • 2020-11-29 13:53

    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 complex objects, use something like jQuery's clone(), credit @Jonathan.

    0 讨论(0)
  • 2020-11-29 14:00

    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 讨论(0)
  • 2020-11-29 14:04

    Am I just creating a reference to the labelArray […] ?

    Yes, exactly. valueArray and labelArray still identify the same object, which hasn't been copied.

    0 讨论(0)
提交回复
热议问题