noobjavascript递归

noobjavascript递归,javascript,recursion,Javascript,Recursion,我是一名系统管理员,试图学习javascript作为第一语言。我正在学习的一篇文章在递归一章中有这个代码示例 (为简单起见,变量已更改) 我理解函数的三元运算符方面,同样的事情可以写成: function fruit(n) { if n > 1 return fruit(n - 1) + "apples"; else return "bananas"; } 当我调用函数时,我得到以下结果 console.log(fruit(3)); banana

我是一名系统管理员,试图学习javascript作为第一语言。我正在学习的一篇文章在递归一章中有这个代码示例

(为简单起见,变量已更改)

我理解函数的三元运算符方面,同样的事情可以写成:

function fruit(n) {
    if n > 1
      return fruit(n - 1) + "apples";
    else
      return "bananas";
}
当我调用函数时,我得到以下结果

console.log(fruit(3));

bananas apples apples
我不明白第一个值是如何计算的(这难道不意味着条件3>1是错误的吗)?关于如何执行这段代码以得到结果,发生了什么


不确定此站点是否对noob友好,但提前感谢您的帮助。

发生这种情况是因为递归继续进行,如下所示:

function fruit(n) {
if n > 1
  return fruit(n - 1) + "apples";
else
  return "bananas";
}
在您给出的示例(上面列出)中,检查
n>1
。在这种情况下,
n=3
,因此答案是肯定的。那我们该怎么办?我们执行水果(2)

2大于1吗?是的,那我们该怎么办?我们执行水果(1)

1大于1吗?不,所以我们写香蕉

然后递归排序返回轨迹,在返回时编写apple和apple以完成前面的方法

可视示例:
因为我们知道,在计算递归时,函数只有在
n时才会返回“banana”,所以最好从基本情况开始。在本例中,您的基本情况是
fruit(1)
——我希望很明显,它返回的是
香蕉

现在考虑<代码>水果(2)< /代码>这将返回<代码>水果(1)+“苹果”< /代码>,并且我们已经知道<代码>水果(1)< /代码>是代码>香蕉> <代码>,因此这意味着代码>香蕉苹果< /代码>


进一步扩展这个例子-
水果(3)
基本上是
水果(2)+“苹果”
,你已经知道
水果(2)
是什么了。。。您最终得到的结果是“香蕉苹果”+“苹果”

我对您的代码进行了如下测试:

<script>
function fruit(n) {
    console.log("Called with " + n);
    if (n > 1) {
      return fruit(n - 1) + "apples ";
    } else {
      console.log("Called with " + n + " returning bananas.");
      return "bananas ";
    }
}
console.log(fruit(3));
</script>
该行返回水果(n-1)+“苹果”;意思是连接一个字符串:“香蕉”+“苹果”+“苹果”

看看每一步:

fruit(3):
- calling fruit(2)
- - calling fruit(1)
- - get return "bananas" // string consinst of "bananas" only here
- get return "apple" // string = "bananas" + "apple"
get return "apple" // string = "bananas" + "apple" + "apple"
编辑: 如果你想在最后吃香蕉。 改变


第一个条件再次调用水果。在纸上运行代码。这是一个很好的解释方法。
fruit(3) = [fruit(1) apples] apples
fruit(3) = [(banana) apples] apples
<script>
function fruit(n) {
    console.log("Called with " + n);
    if (n > 1) {
      return fruit(n - 1) + "apples ";
    } else {
      console.log("Called with " + n + " returning bananas.");
      return "bananas ";
    }
}
console.log(fruit(3));
</script>
Called with 3
Called with 2
Called with 1
Called with 1 returning bananas.
bananas apples apples 
fruit(3):
- calling fruit(2)
- - calling fruit(1)
- - get return "bananas" // string consinst of "bananas" only here
- get return "apple" // string = "bananas" + "apple"
get return "apple" // string = "bananas" + "apple" + "apple"
return fruit(n - 1) + "apples ";
return "apples " + fruit(n - 1);