[英]Javascript i++ too much recursion, i+1 ok in tail recursion
thanks for your time. 谢谢你的时间。
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))
As the arguments.callee is forbidden in strict mode after ES5, so I replace it with a function name. 由于在ES5之后严格模式中禁止arguments.callee,所以我用函数名替换它。 After which, I saw the i + 1 part, and I replace it with an i++, which turns out too much recursion. 之后,我看到了i + 1部分,我用i ++替换它,结果是太多的递归。
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))
After a few debug, I found out that the i + 1 works fine, while i++ does not. 经过几次调试后,我发现i + 1工作正常,而i ++没有。
So, did I use i++ the wrong place or I havent understood i++ at all? 那么,我使用i ++是错误的地方还是我根本不了解i ++?
Thnx again. Thnx再次。
i++
increments a number and returns the old value . i++
递增一个数字并返回旧值 。
This means effectively that you're passing i
everywhere instead of i + 1
. 这意味着有效的,你路过i
无处不在,而不是i + 1
。
It's better to just pass i + 1
since that's the value you're asking for - but ++i
will also work. 最好只传递i + 1
因为这是你要求的价值 - 但++i
也会工作。
i+1
means "return value that is one larger than i , don't change i " i+1
表示“返回值比我大1,不要改变我 ”
i++
means "increment i by one, but return the original value" i++
表示“逐个递增i ,但返回原始值”
++i
means "increment i by one and return the incremented value" ++i
意思是“将i递增1并返回递增的值”
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. 因此,在这种情况下,如果你使用i+1
你不会改变i的值,但你发送一个大于i的值作为参数。 You could also use the ++i
, if you would need the value in i to change also. 你也可以使用++i
,如果你还需要i中的值来改变。
Examples 例子
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
The same applies also for i-1
, i--
and --i
这同样适用于i-1
, i--
和--i
This is because only the output of i++
is the same as i + 1
. 这是因为只有i++
的输出与i + 1
相同。
But when you use i++
you also assign the value to i
. 但是当你使用i++
你也将值赋给i
。
so 所以
var i = 0;
output i++; // 1
output i; // still 1
var i = 0;
output i + 1; // 1
output i; // 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.