最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - For loop in JS only returns first value? - Stack Overflow

programmeradmin1浏览0评论

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 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;
  }
};

console.log(FirstFactorial(5));

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 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;
  }
};

console.log(FirstFactorial(5));

Share Improve this question edited Nov 16, 2022 at 9:33 Ivar 6,86812 gold badges56 silver badges67 bronze badges asked May 6, 2014 at 19:20 mercurymercury 191 silver badge1 bronze badge 3
  • 5 you should look up recursion... because you are attempting to do it, but you aren't – El Guapo Commented May 6, 2014 at 19:21
  • move the return statement outside of your for loop, it will stop executing when you hit a return statement and not actually loop. – doublesharp Commented May 6, 2014 at 19:22
  • also more standard to use a lower case for functions, capitalize objects, so firstFactorial() would be a more appropriate name. – doublesharp Commented May 6, 2014 at 19:23
Add a ment  | 

4 Answers 4

Reset to default 5

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 pleted.

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.

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/DuLpr/2/

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;
};

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));
发布评论

评论列表(0)

  1. 暂无评论