Creating a list from an array
You're having trouble with an exercise from the Javascript Eloquent Book . The challenge is to create a list from an array.
The list looks something like this:
var list = {
value: 1,
rest: {
value: 2,
rest: {
value: 3,
rest: null
}
}
};
Solution on the book website :
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 I don't understand why. As I could imagine, the loop will overwrite the list object, while its rest property points to the object that contains it. Can anyone explain to me how and why it works?
I have also tried the solution in my browser (Firefox 33) and it console.log(arrayToList([10,20]))
prints "undefined"
source to share
It runs at the end of the array, wrapping the previous result with a new object each time, which means that the structure gets deeper and deeper.
Goes though it is loop by loop for an array [1,2,3]
First cycle:
i = 2 array[2] is 3 list = {value: 3, rest: null}
Second:
i = 1
array[1] is 2
list = {value: 2, rest: {value: 3, rest: null}}
Third and last:
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>
source to share