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"