Reputation:
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!
Upvotes: 0
Views: 73
Reputation: 104775
You subtract 1
for i
in the middle of the loop if it's not 0
- so it never finishes the for
- you can use recursion for this!
function addToList(obj, arr, index) {
obj.value = arr[index];
if (index == (arr.length - 1)) {
obj.rest = null
} else {
obj.rest = {};
addToList(obj.rest, arr, index + 1)
}
}
var myObj = {};
var arr = [1,2,3];
addToList(myObj, arr, 0)
Demo: http://jsfiddle.net/freab275/
Upvotes: 1
Reputation: 12214
You are playing games with your loop counter and the recursion. Each time i
is not 0 you subtract one, then the loop adds one. So with one step back and one step forward you never finish. Add some print statements to see what i
is each time you reference it.
Upvotes: 0