Change the value of an array changes original array JavaScript

前端 未结 3 737
面向向阳花
面向向阳花 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.

提交回复
热议问题