javascript - Javascript 函数将我的值转换为 undefined。我和我的老师不明白为什么
问题描述
我今天来这里是因为我(和我的老师)在 javascript 中不理解的错误。
下面的代码只是一个函数的阶乘(强制用函数来做)。但是返回时我的值在未定义中发生了变化。
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);
}
}
我不明白为什么它返回未定义。有人可以解释一下吗?此外,如果该功能仅在该功能中执行一次,则该功能将起作用。
先感谢您。
解决方案
您必须返回递归调用,否则第一次调用facto
永远不会遇到return
语句,导致第一次调用(默认情况下)返回undefined
. 更改为return facto(chiffre, fact);
:
var test;
do {
var result = parseInt(prompt("Un chiffre supérieur à 1"));
} while (isNaN(result) || result < 2);
test = facto(result, 1);
console.log(test);
function facto(chiffre, fact) {
fact = fact * chiffre;
chiffre = chiffre - 1;
if (chiffre == 1) {
return fact;
} else {
return facto(chiffre, fact);
}
}
推荐阅读
- python - 是否可以通过 TFLite Model Maker 创建多类文本分类器 Tensorflow Lite 模型?
- dataframe - spark中的lit()有什么用?下面两段代码返回相同的输出,使用 lit() 有什么好处
- javascript - Javascript:MediaRecorder 下载的录音不播放
- user-interface - 如何在 Flutter 的 Listview 中对齐文本和图标?
- javascript - 反应图像源
- python - 如何按项目类型对熊猫数据框列进行排序?
- python-3.x - 根据值范围更改颜色图中的颜色
- java - @RequestMapping 没有 @ResponseBody 的不同行为
- reactjs - 如何将按钮折叠起来?
- kubernetes - 重复的大使映射是否会导致 Kubernetes 服务失效?