문제 설명
arrayToList가 홀수 출력을 생성합니다. 뭐가 문제 야? (arrayToList producing odd outputs. What's wrong?)
저는 책에서 이 연습을 하고 있었는데 배열을 목록으로 변환하는 함수를 작성하도록 요청합니다(값을 저장하는 "value" 속성과 다음 값을 가리키는 "rest" 속성을 가진 객체) ).
이 책에서 제공하는 솔루션은 다음과 같습니다.
function arrayToList(array) {
var list = null;
for (var i = array.length ‑ 1; i >= 0; i‑‑)
list = {value: array[i], rest: list};
return list;
}
console.log(arrayToList([10, 20, 30]));
// → {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}
제가 생각해낸 솔루션은 다음과 같습니다.
function arrayToList(array){
var list = {value: null, rest: null};
var tempList={value: array[array.length‑1], rest: null};
for(var i=array.length‑2; i>=0;i‑‑){
list.value = array[i];
list.rest = tempList;
tempList = list;
}
return list;
};
console.log(arrayToList([10, 20, 30]));
하지만 이렇게 하면 다음과 같은 결과가 나옵니다.
{value: 10, rest: {value: 10, rest: {value: 10, …}}}
요소 2개로 구성된 배열과 그 이상에서 작동하며 10초의 루프가 발생합니다. 정확히 어디에서 이런 일이 발생하는지 확인하기 위해 코드를 분석하려고 했습니다... tempList에 목록이 할당된 위치인 것 같습니다.
누군가 나에게 무엇이 잘못되었는지 설명할 수 있습니까?
참조 솔루션
방법 1:
Javascript objects are, essentially, call by reference. So when you are setting tempList to list, you are simply creating a pointer, not a copy, and therefore the second time through the loop, you set list.rest to point back to itself, thus creating an infinite rest‑> {10, rest ‑> {10, rest ‑> 10 ..... what you want to do is "point" list to a new object, like in the book's solution.
(by Tamir K Yirga、Leroy Stav)