For loop in JS only returns first value?

2020-05-09 22:24发布

I've created a loop in JS to calculate factorials - however, instead of getting the factorial, I'm just only getting the first value of the for loop. In the code below, I'm just getting 1 for show(FirstFactorial(5));

Any ideas on what's wrong here...?

function FirstFactorial (num) { 
  var myVar=1;
  for(var i=1; i<=num; i++){
    myVar=myVar*i;
    return myVar;
}
};

show(FirstFactorial(5));

4条回答
SAY GOODBYE
2楼-- · 2020-05-09 22:42

Your loop actually returns when it first reaches the return and never runs after. This is how return works, returning back to where it was called. You would be better to place your return to run AFTER the loop has completed.

function FirstFactorial (num) { 
  var myVar=1;
  for(var i=1; i<=num; i++){
    myVar=myVar*i;
  }
  return myVar;
};

show(FirstFactorial(5));

Here is a JSFiddle of the result.

查看更多
我想做一个坏孩纸
3楼-- · 2020-05-09 22:48

By using recursion, you can achieve much smaller code and eliminate the need for a for loop:

function factorial(n) { 
    return n > 1 ? n * factorial(n-1) : (n == 0) ? 1 : n;
}

console.log(factorial(5));

Returns:

120

jsFiddle: http://jsfiddle.net/DuLpr/2/

查看更多
闹够了就滚
4楼-- · 2020-05-09 22:51

You need to have your return statement outside of the loop:

function FirstFactorial (num) { 
    var myVar=1;
    for(var i=1; i<=num; i++){
        myVar=myVar*i;

    }
    return myVar;
};
查看更多
5楼-- · 2020-05-09 22:54

Take the return statement outside of your for loop:

function FirstFactorial (num) { 
  var myVar=1;
  for(var i=1; i<=num; i++){
    myVar=myVar*i;
    }
return myVar;
};

show(FirstFactorial(5));
查看更多
登录 后发表回答