为什么这个递归函数没有返回值 [英] Why is this recursive function not returning the value

查看:65
本文介绍了为什么这个递归函数没有返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

注释掉的第 n 个函数做了本书想要的,但它不是递归的.还有一些额外的 console.log() 用于调试.如您所见,当我记录成功"和值时,它将记录正确的值.但是,当我之后立即返回相同的值时,它返回 undefined.

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.

推荐答案

您需要从递归中返回值...

You need to return the value from you recursion...

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);
  }
}

这样想-

初始调用 I 失败,因此您递归 R1 并失败,然后递归 R2 并成功.

Initial call I fails, so you recurse R1 and fail, then recurse R2 and succeed.

您正确地将值从 R2 返回到 R1,但随后必须从 R1 返回到 I并退出函数.

You correctly return the value from R2 to R1, but you must then return from R1 to I and back out the function.

这篇关于为什么这个递归函数没有返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆