简体   繁体   English

阶乘函数返回未定义

[英]factorial function returns undefined

This a simple code for factorial, I have written the function and it loops through giving right output but at the end, it returns undefined.这是阶乘的简单代码,我编写了该函数,它通过提供正确的输出进行循环,但最后返回未定义。 I don't know why.我不知道为什么。

function factorial(n){
    let value=1; 
    for(let i=1;i<=n;i++) {
        value = i*value; 
        console.log(value); 
    }  
}

Because you do not return anything from the function, so undefined is the result of its work.因为你没有从函数中返回任何东西,所以undefined是它工作的结果。 You need to return the value explicitly:您需要明确返回值:

function factorial(n){
  let value=1;

  for(let i=1;i<=n;i++) {
    value = i*value; 
    console.log(value); 
  } 

  return value;
}

You can find factorial by using recursion.您可以使用递归找到阶乘。 Here is the implementation.这是实现。

 function factorial(x){ if(x == 0) //Exit condition return 1; return x * factorial(x-1); //5*4*3*2*1 } console.log(factorial(5));

This is good implementation:这是一个很好的实现:

const factorial = n => n > 1 ? n * factorial(--n) : 1;

And your function does not have return , so it returns undefined ;而且你的函数没有return ,所以它返回undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM