【发布时间】:2018-11-28 03:43:44
【问题描述】:
我今天来到这里是因为我(和我的老师)在 javascript 中出现了一个我不理解的错误。
下面的代码只是一个函数的阶乘(强制用函数来做)。但是我的值在返回时更改为 undefined。
var test;
do {
var result = parseInt(prompt("Un chiffre supérieur à 1"));
} while (isNaN(result) || result < 2);
// Just asking for a number > à 1 it work //
test = facto(result, 1);
console.log(test);
// The test variable was used to try to understand the bug //
function facto(chiffre, fact) {
// Function for the factorial //
fact = fact * chiffre;
// fact was defined as 1 for the first entry, for others it's gonna be his last result //`
console.log(fact);
chiffre = chiffre - 1;
// We decrase chiffre by one for the next passage //
if (chiffre == 1) {
// if chiffre = 1, we don't need to do other passage, so we return value
console.log(fact);
return fact;
// the result is correct, it's a number. However it return undefined //
} else {
// if chiffre > 1, we continue the math by coming again in the function //
console.log(chiffre);
facto(chiffre, fact);
}
}
我不明白为什么它返回未定义。有人可以解释一下吗? 此外,如果它只在函数中执行一次,该函数就可以工作。
提前谢谢你。
【问题讨论】:
-
您的递归调用丢失了
return。你应该在最后有return facto(chiffre, fact);。
标签: javascript function undefined