Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

javascript - Why is this recursive function not returning the value

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To use recursion, function call must be returned

return nth(list,index);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...