0
function arrayToList(array) {
  var list = null
  for (var i = 0; i < array.length; i++)
    list = {value: array[i], rest: list};
  return list;
}

console.log(arrayToList([10, 20, 30]));

// {value:  30, rest:{ value:20, rest:{value: 10, rest: null}}

I've looked at this function from eloquent javascript exercise for hours, and can't get it why the result are reversed. Any help would be appreciated.

3
  • 4
    Where is the recursion? Commented Mar 24, 2015 at 18:02
  • Edited. Sorry for the confusion. I used a wrong concept. Commented Mar 24, 2015 at 18:04
  • What is the expected output from your arrayToList() function? Commented Mar 24, 2015 at 18:47

2 Answers 2

2

Here's what's happening when you are iterating in your for-loop:

First iteration: i = 0; list = {value:10, rest:null}

Second iteration: i = 1; list = {value:20, rest:{value:10, rest: null}}

Third iteration: i = 2; list = {value:30, rest:{value:20, rest:{value:10, rest: null}}}

On each iteration, you are nesting your list object within itself:

list = {value: array[i], rest: list};

Sign up to request clarification or add additional context in comments.

Comments

1

Set an output in the loop, than you can see how it works:

function arrayToList(array) {
    var list = null
    for(var i = 0; i < array.length; i++) {
        list = {value: array[i], rest: list};
        console.log(list);
        console.log('\n');
    }

    return list;
}

arrayToList([10, 20, 30]);

/* Output

{ value: 10, rest: null }

{ value: 20, rest: { value: 10, rest: null } }

{ value: 30, rest: { value: 20, rest: { value: 10, rest: null } } }

*/

You have set list = null.

The first time in the loop, list is "{ value: 10, rest: null }"

-> "null" nested within.

The second time in the loop, list is "{ value: 20, rest: { value: 10, rest: null } }"

-> "{ value: 10, rest: null }" nested within.

For the last time, list is "{ value: 30, rest: { value: 20, rest: { value: 10, rest: null } } }"

-> "{ value: 20, rest: { value: 10, rest: null } }" nested within.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.