【问题标题】:Javascript function transfomr my value in undefined. Me and my teacher does'nt understand whyJavascript 函数将我的值转换为 undefined。我和我的老师不明白为什么
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • @NiettheDarkAbsol 你的话有点太绝对了。老师不是天才,有时我们不会注意到我们注意到的简单事情。这只是人类。
  • 谢谢。我明白。是的,老师也是人,可以像我们一样错过一些事情;)!
猜你喜欢
  • 2021-10-20
  • 2020-04-23
  • 2016-07-10
  • 2021-11-18
  • 2020-04-30
  • 2018-06-30
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
相关资源
最近更新 更多