I have been following the ebook Eloquent Javascript to learn javascript. In chapter 4 there is a challenge to access the nth value of a list using a recursive function. I have written a recursive function to do just that, but even though I can access the correct value, I can't return it for some frustrating reason.
I'm not sure if the definition of a list used by the book is universal so I here is an explanation. Basically each list element holds both a value, and the next list element. It's like some sort of inception. Here is an example.
list = {
value: 1,
rest: {
value: 2,
rest: {
value 3,
rest: null
}
}
}
So here is the code I am having a problem with.
function arrayToList(array){
var list = {rest:null};
for(var i = array.length-1; i>=0;i--){
list = {
value:array[i],
rest:list
}
}
return list;
}
/*
function nth(list, element){
for(var i = 0;i < element;i++){
list = list.rest;
}
return list.value;
}
*/
function nth(list, index){
console.log(index);
if(index < 1){
console.log("Success", list.value);
return list.value;
}
else {
console.log("Fail");
list = list.rest;
index--;
//console.log(index);
nth(list,index);
}
}
console.log(nth(arrayToList([10, 20, 30]), 1));
// → 20
The commented out nth function does what the book wants, but it's not recursive. Also there are a couple of extra console.log()
s for debugging. As you can see, when I log "Success" and the value, it will log the correct value. However when I return the same value immediately afterward it returns undefined.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…