我是一名系统管理员,试图将javascript作为第一语言学习。我正在研究的其中一个文本在递归章节中有这个代码示例。
(为简单起见改变了变量)
function fruit(n) {
return n > 1 ? fruit(n - 1) + "apples" : "bananas";
}
我理解函数的三元运算符方面,同样的事情可以写成:
function fruit(n) {
if n > 1
return fruit(n - 1) + "apples";
else
return "bananas";
}
当我调用该函数时,我得到以下结果
console.log(fruit(3));
bananas apples apples
我不明白香蕉的第一个值是怎么样的(这不意味着条件3> 1会是假的)?关于如何执行此代码以获得该结果会发生什么?
不确定此网站是否友好,但提前感谢您的帮助。
答案 0 :(得分:4)
在计算递归时,最好从基本情况开始。在这种情况下,您的基本案例为fruit(1)
- 我希望很明显这会返回bananas
。
现在考虑fruit(2)
- 这将返回fruit(1) + "apples"
,我们已经知道fruit(1)
为bananas
,因此这意味着bananas apples
。
进一步扩展此案例 - fruit(3)
基本上是fruit(2) + "apples"
,您已经知道fruit(2)
是什么......您最终得到"bananas apples" + "apples"
,并向您提供结果。
答案 1 :(得分:1)
我已经测试了您的代码,如下所示:
<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
该行返回水果(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"
编辑: 如果你想在最后吃香蕉。 变化
return fruit(n - 1) + "apples ";
到
return "apples " + fruit(n - 1);
答案 2 :(得分:0)
这是因为递归继续如下:
function fruit(n) {
if n > 1
return fruit(n - 1) + "apples";
else
return "bananas";
}
在您给出的示例中(上面列出),您可以查看是否n > 1
。在这种情况下n = 3
所以答案是肯定的。那么我们该怎么办?我们执行水果(2)。
2大于1吗?是的,那我们该怎么办?我们执行水果(1)。
是1&gt; 1?不,所以我们写香蕉。
然后递归一些回溯,在回归时写下苹果和苹果以完成之前的方法。
视觉示例:
因为我们知道该函数仅在n <= 1
function fruit(3)
将返回SOMETHING,然后写“苹果”
fruit(3) = fruit(2) apples
fruit(2) = fruit(1) apples
fruit(1) = banana
所以你看,因此替换[fruit(2)]
和(fruit(1))
:
fruit(3) = [fruit(1) apples] apples
fruit(3) = [(banana) apples] apples