Reputation: 87
Having trouble with an exercise from the Eloquent Javascript book. The task is to create a list out of an array.
The list is something like this:
var list = {
value: 1,
rest: {
value: 2,
rest: {
value: 3,
rest: null
}
}
};
The solution on the website of the book is:
function arrayToList(array)
{
var list = null;
for (var i = array.length-1; i>=0; i--) {
list = {value: array[i], rest: list};
}
return list;
}
I understand how it works, but don't get why. As I would have imagined the loop would rewrite the list object, while its rest property would point to the object that contains it. Can someone explain me how and why it works?
I have also tried the solution in my browser (Firefox 33) and console.log(arrayToList([10,20]))
prints out "undefined"
Upvotes: 3
Views: 1093
Reputation: 54801
It starts at the end of the array wrapping the previous result in a new object each time, meaning the structure gets deeper and deeper.
Going though it loop by loop for array [1,2,3]
The first loop:
i = 2
array[2] is 3
list = {value: 3, rest: null}
The second:
i = 1
array[1] is 2
list = {value: 2, rest: {value: 3, rest: null}}
The third and final:
i = 0
array[0] is 1
list = {value: 1, rest: {value: 2, rest: {value: 3, rest: null}}}
As for printing undefined
, I don't understand why, but this works:
function arrayToList(array)
{
var list = null;
for (var i = array.length-1; i>=0; i--) {
list = {value: array[i], rest: list};
}
return list;
}
$('#A').html(JSON.stringify(arrayToList([1, 2, 3])));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="A">test</div>
Upvotes: 4