简体   繁体   English

JavaScript中的递归函数

[英]Recursive functions in JavaScript

Please help me understand this recursive function... 请帮助我了解此递归函数...

var stack = Array;
function power(base, exponent){
    if ( exponent === 0 ) {
        return 1;
    } else {
        stack[exponent-1] = base * power(base, exponent - 1);
        return stack[exponent-1];
    }
}

I dont understand what 我不明白

stack[exponent-1]
is doing 是在做

Which one? 哪一个? It's called twice. 这叫两次。 But each time it's either getting the value that exists in the array at the index equal to the current value of exponent-1 or setting that value. 但是每次它要么获取数组中存在于索引处的值等于exponent-1的当前值,要么设置该值。

It's just an array index and access. 它只是一个数组索引和访问。

have a look on this version! 看看这个版本!

function pow(x,n)
{
     return n==0?1:n==1?x:n==2?x*x:pow(pow(x,(n-n%2)/2),2)*(n%2==0?1:x);
}

can get it shorter? 可以缩短它的时间?

The algorithm is stacking the result of each power from the initial exponent to 0. 该算法每个幂的结果从初始指数堆叠到0。

If you run power(2, 3) , the stack will, at some point, be: 如果运行power(2, 3) ,则堆栈在某些时候将为:

stack[2] = 8
stack[1] = 4
stack[0] = 2

This really has nothing to do with the mathematic concept of power. 这实际上与幂的数学概念无关。

I did console log of stack[exponent-1] using 我使用以下命令管理了stack [exponent-1]的控制台日志

var stack = Array;
function power(base, exponent){
    if ( exponent === 0 ) {
        return 1;
    } else {
        stack[exponent-1] = base * power(base, exponent - 1);
        console.log(stack[exponent-1]);return stack[exponent-1];
    }
}

O/P: O / P:

power(2,5)
2
4
8
16
32

So function class recursively until exponent become 0 (nth call), then it will start returning results 因此,函数类递归直到指数变为0(第n次调用),然后它将开始返回结果

first it will return 1     (because exponent is 0)
        then returns 2 * 1 (return of n call)
              then   2 * 2 (return of n-1 call) 
              then   2 * 4 (return of n-2 call) and so on

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM