카테고리 없음

[자바 스크립트] 다차원 자바 스크립트 배열에 새 항목 추가

행복을전해요 2021. 2. 25. 06:50

It's an object reference problem - Arrays are objects, so when you modify [0] and [1], you're modifying it in both places. Use a slice to copy the contents:

var multiArray = [],
  singleArray = [];
  
  singleArray[0] = "10";
  singleArray[1] = "11";
  
  multiArray.push(singleArray.slice(0));
  
  singleArray[0] = "20";
  singleArray[1] = "21";
  
  multiArray.push(singleArray);
  
  console.log(multiArray); // [["10", "11"], ["20", "21"]]
  
-------------------

Lots of ways to do this and get what you want . . . the other two answers will do it, as will these two approaches:

multiArray.push(["10", "11"]);
multiArray.push(["20", "21"]);

. . . and . . .

multiArray.push(new Array("10", "11"));
multiArray.push(new Array("20", "21"));

Both result in an array of: [["10", "11"], ["20", "21"]]

In the end, the important thing is that you need to create a new array instance for each set of values that you store, since the outer array will just be storing pointers to each inner array that it contains.

-------------------

당신은 배열의 사본을 밀어 넣는 것이 아닙니다. 배열 에 대한 참조 사본을 푸시하고 있습니다. 복사본이 모두 동일한 배열을 가리 키므로 두 번 표시됩니다.

간단하게 다음과 같이 할 수 있습니다.

multiArray.push([10,11], [20,21])

또 다른 방법은 이렇게하는 것입니다.

multiArray.push(JSON.parse(JSON.stringify(singleArray)));
  

여기서 배열을 문자열 화 한 다음 다시 구문 분석하여 사실상 새 배열을 만듭니다. 당신이 원한다면 일종의 "복제".

slice이 특정 시나리오에서는 사용 이 더 나은 대안입니다.

multiArray.push(singleArray.slice(0));


출처
https://stackoverflow.com/questions/22080105