首页 > 解决方案 > 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);
  }
}

我不明白为什么它返回未定义。有人可以解释一下吗?此外,如果该功能仅在该功能中执行一次,则该功能将起作用。

先感谢您。

标签: javascriptfunctionundefined

解决方案


您必须返回递归调用,否则第一次调用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);
  }
}


推荐阅读