2017-08-24 139 views
-3

所以,一位朋友向我分享了这个代码,并且我很难理解它是如何提供正确的结果的,因为它没有经过一个循环。如果有人能像我这样向我解释它5我真的很感激它。有人可以向我解释这段代码的工作原理吗?

function fact(n){ 
    if(n === 1){ 
    return 1; 
    }else{ 
    return n * fact(n - 1); 
    }; 
}; 
console.log(fact(5)); 
+3

您的Google关键字是'recursion' –

+0

它使用循环;它是递归的。查找递归工作。这*确切*代码已被解释过很多次。 – Carcigenicate

+3

你的朋友拒绝向你解释吗? – BoltClock

回答

0

在阶乘的属性,n!可被写入为n * (n-1) ! 。 也就是说,n的函数的结果可以作为获得n倍该函数的结果为n-1,等等,以1:

function factorial(n) { 
    return (n != 1) ? n * factorial(n - 1) : 1; 
} 

alert(factorial(5)); // 120 

递归基础是值1。你可以使基础和0。然后,代码会更短一点:

function factorial(n) { 
    return n ? n * factorial(n - 1) : 1; 
} 

alert(factorial(5)); // 120 

在这种情况下,呼叫factorial (1)减小到1 * factorial (0),会有递归的附加步骤。

0

该代码是一个递归函数调用来获取数字的阶乘。

function fact(n){ // function declaration 
    if(n === 1){ //strict type check if n is an integer 1 not a '1' 
    return 1; // return back 1 
    }else{ // if n is not 1 
    return n * fact(n - 1); //return the number n multiplied by the function call fact again in which the parameter is n-1 now. 
    }; 
}; 
console.log(fact(5)); //print the result of function call fact(5) and print it to console. 

function fact(n){ 
 
    if(n === 1){ 
 
    return 1; 
 
    }else{ 
 
    return n * fact(n - 1); 
 
    }; 
 
}; 
 
console.log(fact(5));

它是运行在数学公式的呼叫来计算阶乘:

n * (n-1) ! 
0

当涉及到递归时,你可以把它看作一个调用自己的函数;在这种情况下

function fact(n){ 
    //test to see if n is 1, if so just return 1 
    if(n === 1) 
     return 1; 
    // multiply n by the result of calling fact(n-1) 
    return n * fact(n - 1); 
} 

console.log(fact(5)); 

所以当你调用这个案件事实(5) 你会得到 5 *事实(5-1)= 4 *事实(4-1)= 3 *事实(3- 1)= 2 *事实(2-1)= 1

导致5 * 4 * 3 * 2 * 1 = 120

它有点棘手的一个概念,以在第一弄清楚,尝试插入console.log加入到函数中,让您更清楚地了解发生了什么。

function fact(n){ 
    console.log(n); 
    //test to see if n is 1, if so just return 1 
    if(n === 1) 
     return 1; 
    // multiply n by the result of calling fact(n-1) 
    return n * fact(n - 1); 
} 
+0

谢谢,这是一个更清晰的解释。欣赏它。 – Nar

+0

没有问题我应该提及递归的一个基本原理是每个递归函数都需要一个退出条件,在这个例子中它是(n === 1)return 1;如果退出条件不存在,那么你会陷入无限循环。 – Pav

相关问题