[英]Confusion about the behavior between arithmetic operators and functions?
function pow(x, n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n - 1);
}
}
alert( pow(2, 3) ); // 8
source = https://javascript.info/recursion来源 = https://javascript.info/recursion
Hello all: I'm confused about the second return statement of this function:大家好:我对这个函数的第二个返回语句感到困惑:
return x * pow(x, n - 1);
I'm just looking for either some clarification or a reference to that behavior.我只是在寻找一些澄清或对该行为的参考。
From my perspective, it looks like x is multiplied only by the first parameter of the function, and the n-1 is ignored.在我看来,看起来 x 只乘以 function 的第一个参数,而忽略了n-1 。
(How does n-1 affect the result <- original question) (n-1如何影响结果<-原始问题)
Sorry, I messed up the original question... I want to ask how does javascript interprets that multiplication.抱歉,我把原来的问题搞砸了……我想问一下 javascript 如何解释那个乘法。 When multiplying an integer and a function, I don't quite understand what's happening.
将 integer 和 function 相乘时,我不太明白发生了什么。 How does javascript choose what to multiply with more than one parameter?
javascript 如何选择与多个参数相乘的内容?
pow(2, 3) = 2 * pow(2, 2) = 2 * 2 * pow(2, 1) = 2 * 2 * 2 pow(2, 3) = 2 * pow(2, 2) = 2 * 2 * pow(2, 1) = 2 * 2 * 2
You are not actually calculating a product with n - 1, but refer to n as a counter.您实际上并不是在计算具有 n - 1 的产品,而是将 n 称为计数器。 This is equivalent to
这相当于
var result = 1;
while (n >= 0) {
result *= x;
n--;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.