2016-07-28 123 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