2016-07-28 126 views
-2

我一直在关注电子书Eloquent Javascript来学习JavaScript。在第4章中,使用递归函数访问列表的第n个值是一个挑战。我已经写了一个递归函数来做到这一点,但即使我可以访问正确的值,但由于一些令人沮丧的原因,我无法返回它。为什么这个递归函数没有返回值

我不确定本书使用的清单的定义是否通用,所以我在这里解释一下。基本上每个列表元素都包含一个值和下一个列表元素。这就像某种初始状态。这是一个例子。

list = { 
    value: 1, 
    rest: { 
     value: 2, 
     rest: { 
      value 3, 
      rest: null 
     } 
    } 
} 

所以这里是我遇到问题的代码。

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 

注释掉的第n个函数完成本书想要的内容,但它不是递归的。另外还有一些额外的console.log()用于调试。正如你所看到的,当我登录“成功”和值时,它会记录正确的值。但是,当我立即返回相同的值时,它将返回undefined。

+0

忘记返回功能值,我们已经回答了几十次。由于某些原因,我找不到重复的参考。 – Prune

+0

我怎么会知道这是我的问题,除非我问?如果我不知道问题是什么,我无法搜索问题的答案。 – Supetorus

回答

2

您需要返回从你递归的价值...

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--; 
    return nth(list,index); 
    } 
} 

这样想 -

初始呼叫失败,所以你递归R1并失败,然后递归R2并成功。

你正确地从R2返回值R1,但你必须返回从R1和背出功能。

+0

这实际上是有道理的,让我试试看。 – Supetorus

+0

我一定要重新访问这个。这完全煎炸了我的大脑。谢谢您的帮助! – Supetorus

3

使用递归,函数调用必须返回

return nth(list,index); 
+0

对不起,我不明白。我尝试了以下两种方式,但都无法正常工作。 函数nth(list,index){ \t if(index <1){ \t return nth(list,index); \t} \t else { \t list = list.rest; \t index--; \t return nth(list,index); \t} \t} \t功能第n(列表中,索引){ \t如果(索引=== 0){ \t返回第n(列表中,索引); \t} else { \t index--; \t list = list。休息; \t} \t} – Supetorus