I am learning JavaScript from a book called 'Eloquent Javascript'
I'm trying to solve the exercise described here: http://eloquentjavascript.net/04_data.html#h_nSTX34CM1M
I managed to work out that this code works:
function arrayToList(array) {
var list = null;
for (var i = array.length - 1; i >= 0; i--)
list = {
value: array[i],
rest: list
};
return list;
}
console.log(arrayToList([1, 2, 3]));
Result: { value: 1, rest: { value: 2, rest: { value: 3, rest: null } } }
So far, so good, and according to the book this is the right solution. BUT!
When I try to run the same thing but instead with a longer array, let's say:
console.log(arrayToList([1, 2, 3, 4, 5]));
The result is: { value: 1, rest: { value: 2, rest: { value: 3, rest: [Object] } } }
Why is this? Is my code wrong?
There's nothing wrong with a longer array. console.log()
is a non-standard, browser-specific implementation and some implementations set a cap on how many levels of object nesting they will display. When they hit that level, they just display [Object]
rather than recurse into it to show deeper nesting.
If you actually set a breakpoint and examine your variable in the debugger, you will see you can expand the nested levels as deep as it goes and see everything.
Or, you could do this:
console.log(JSON.stringify(arrayToList([1, 2, 3, 4, 5])));
to manually convert the whole thing to a string before using console.log()
on it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.