我有一个函数,它接受一个参数来打印Fibonacci系列中的最后一个数字,例如,如果该参数是3那么它将返回2,因为该系列将变为1,1,2 我的功能
<box1><strong>Note:</strong> Some of these resources are free, and some aren’t. Those that are paid resources are affiliate products or services, meaning if you buy them, I get a commission at no extra cost to you. Please know that I have personal experience
with all of the following resources, which is why I recommend them.</box1>
&#13;
不,我想在这个函数中使用闭包,这样我就可以打印整个系列,而不仅仅是系列的最后一个数字。
答案 0 :(得分:0)
当您使用递归时,您需要一个不会破坏该模式的打印功能。
function print_and_forward(value) {
console.log(value);
return value;
}
您可以在return语句中使用它来打印值,然后将其返回。具体来说,试试
function recursionFib(num){
if(num==0) return print_and_forward(0);
if(num==1) return print_and_forward(1);
return print_and_forward(recursionFib(num-1)+recursionFib(num-2));
}
那将打印计算树。如果您只希望系列只打印recursionFib(num-1)
的结果,然后打印总计。