arrayToList가 홀수 출력을 생성합니다. 뭐가 문제 야? (arrayToList producing odd outputs. What's wrong?)


문제 설명

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 YirgaLeroy Stav)

참조 문서

  1. arrayToList producing odd outputs. What's wrong? (CC BY‑SA 2.5/3.0/4.0)

#list #data-structures #linked-list #arrays #javascript






관련 질문

파이썬에서 데이터를 정렬하는 방법 (How arrange data in python)

포스트백 후 모든 항목이 손실되는 CheckBoxList 컨트롤 (CheckBoxList control losing all items after post back)

목록 목록의 효과적인 구현 (Effective implementation of list of lists)

DictReader가 내 파일의 두 줄을 건너뛰고 있습니까? (DictReader is skipping two lines of my file?)

잘못된 값을 얻는 목록 확인 후 (After list checking getting wrong value)

결과를 세로 방향으로 저장하는 방법 (How do i save the result in a Vertical direction)

Python 2.x: 튜플 목록의 항목 합계 (Python 2.x: Summing items in a list of tuples)

itemgetter를 사용하지 않고 n번 발생하는 요소가 있는 목록 내 항목 인쇄 (Printing items inside a list which have an element that occurs n times without using itemgetter)

반환된 목록에서 장소가 바뀐 항목 삭제 (Deleting items that have the place swapped around in a returned list)

arrayToList가 홀수 출력을 생성합니다. 뭐가 문제 야? (arrayToList producing odd outputs. What's wrong?)

R 목록을 벡터로 바꾸는 방법과 목록이 필요한 이유 (R how to turn lists to vectors, and why a list at all)

python, 출력으로 코딩하는 동안 pycharm에서 이 메시지를 받았습니다. :TypeError: can't convert type 'list' to numerator/denominator (python , I got this message in pycharm while coding as output :TypeError: can't convert type 'list' to numerator/denominator)







코멘트