This is the 3rd question from Eloquent JavaScript chapter 4.
Basically it wants me to create a function that will make an array into a nested list from array.
E.g. arrayToList([1, 2, 3]) should return:
var list = {
value: 1,
rest: {
value: 2,
rest: {
value: 3,
rest: null
}
}
};
I wonder why my code leads to an infinite loop.
function arrayToList(arr) {
var list = {};
for (var i = 0; i < arr.length; i++) {
var a = arr[i];
function add(res) {
if (i == 0) {
res.value = a;
res.rest = "null";
}
else {
i -= 1;
add(res.rest);
}
}
add(list);
}
return list;
}
Thank you for taking a look!