Javascript i ++过多递归,i + 1尾递归确定 [英] Javascript i++ too much recursion, i+1 ok in tail recursion

查看:92
本文介绍了Javascript i ++过多递归,i + 1尾递归确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的时间。

我正在学习斐波纳契函数,其中一个答案如下:

I was learning an Fibonacci function and one of the answer is below:

function fibonacci(n) {
    return (function(a, b, i) {
        return (i < n) ? arguments.callee(b, a + b, i + 1) : a;
    })(1, 1, 1);
}
console.log(fibonacci(51))

作为参数在ES5之后严格模式禁止.callee,所以我用函数名替换它。之后,我看到了i + 1部分,我将其替换为i ++,结果是太多的递归。

As the arguments.callee is forbidden in strict mode after ES5, so I replace it with a function name. After which, I saw the i + 1 part, and I replace it with an i++, which turns out too much recursion.

function x(n){
    return (function y(a, b, i){
        return (i < n) ? y(b, a + b, i++) : a;
    })(1,1,1)
}
console.log(x(51))

经过几次调试后,我发现i + 1工作正常,而i ++没有。

After a few debug, I found out that the i + 1 works fine, while i++ does not.

那么,我在错误的地方使用i ++还是我根本不理解i ++?

So, did I use i++ the wrong place or I havent understood i++ at all?

再次获得Thnx。

推荐答案

i + 1 表示返回值大于1 i ,请勿更改 i

i+1 means "return value that is one larger than i, don't change i"

i ++ 表示将 i 增加1,但返回原始值

i++ means "increment i by one, but return the original value"

++ i 表示将 i 递增1并返回递增的值

++i means "increment i by one and return the incremented value"

所以在这种情况下,如果你使用 i +1 您没有更改 i 的值,但您发送的值大于 i 作为参数。你也可以使用 ++ i ,如果你需要 i 中的值也要改变。

So in this case if you use i+1 you're not changing the value of i, but you're sending a value one larger than i as an argument. You could also use the ++i, if you would need the value in i to change also.

示例

i = 10
a = i+1
// a = 11, i = 10

i = 10
a = i++
// a = 10, i = 11

i = 10
a = ++i
// a = 11, i = 11

这同样适用于 i-1 i - - i

这篇关于Javascript i ++过多递归,i + 1尾递归确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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