functionfactorialIterative(number) {
if (number < 0) {
returnundefined;
}
let total = 1;
for (let n = number; n > 1; n--) {
total = total * n;
}
return total;
}
console.log(factorialIterative(5)); // 120複製代碼
從給定的number開始計算階乘,並減小n,直到它的值爲2。
用遞歸來計算階乘
functionfactorial(n) {
if (n === 1 || n === 0) {
return1;
}
return n * factorial(n - 1);
}
console.log(factorial(3)); // 6複製代碼