javascript 返回for循环内部返回初始值

tkclm6bt  于 2023-02-07  发布在  Java
关注(0)|答案(2)|浏览(194)

我有一个问题,理解为什么在FOR循环中的RETURN总是返回给我初始事实值(让事实= 1):

const factorial = function(a) {
  let fact=1;
  if(a===0){
    return 1;
  }
  else{
    for(let i=1; i<=a; i++){
      fact*=i;
      return fact;**   // This return
    }
    return fact  
  }
  return fact;  
};

//Result for all values e.g 1,5,10 is always 1, as in initial let fact =1

当我去掉它的时候,阶乘函数完全正常,我不知道为什么会这样:

const factorial = function(a) {
  let fact=1;
  if(a===0){
    return 1;
  }
  else{
    for(let i=1; i<=a; i++){
      fact*=i;
      //Nothing
      }
    return fact  
  }
  return fact;  
};
// Code works fine, I receive factorial correctly

我本来希望返回初始值的阶乘,结果却得到了变量的初始值(1)。

yhxst69z

yhxst69z1#

如果我没理解错的话,您可能会想,为什么在第一段代码中,不管输入值是什么,返回值都是1,这是因为在for循环中有一个return语句,这意味着for循环只进入一次,然后退出时返回值为1。这意味着你永远都不能计算阶乘的值,因为 fact = 1 * 2 * 3 * ...,你只需要做第一步,也就是 fact = 1

const factorial = function(a) { // <- you have tested this with 1,5 and 10
  let fact=1;                   // <- here you set fact variable to value of 1
  if(a===0){                    // <- you check if you sent value is equal to 1,
    return 1;                  //     since you have used 1, 5 and 10 you will not be returning a value of 1 here
  }
  else{                        // <- you enter this block of code when the value of a≠0
    for(let i=1; i<=a; i++){   // <- you set the value of i to 1 and you enter the for loop
      fact*=i;                 // <- you multiple your fact value, which is 1, with a value of i, which is also 1, which means you will get fact=1
      return fact;             // <- you return a value of fact, which is 1 here!
    }
    return fact  
  }
  return fact;  
};
z2acfund

z2acfund2#

return运算符未仅中断for循环:it goes deeper and stops whole function.
因此,当您不带任何条件地将return留在for中时,return将在该循环的第一次迭代时停止整个函数(当fact为1时)。
这意味着,你的代码:

const factorial = function(a) {
  let fact=1;
  if(a===0){
    return 1;
  }
  else{
    for(let i=1; i<=a; i++){
      fact*=i;
      return fact; // This return
    }
    return fact  
  }
  return fact;  
};

实际上,等于:

const factorial = function(a) {
  let fact=1;

  if (a === 0){
    return 1;
  } else {
    fact *= 1; // 1 is value of `i` at the first iteration
    return fact;
  }
};

for循环内return运算符的有效条件示例:

function isAnyStringInside(values) {
  for (let i = 0; i < values.length; i += 1) {
    if (typeof values[i] === 'string') {
      return true;
    }
  }

  return false;
}

isAnyStringInside([1,2,3,4,5,'Hello',2,3,4,5]); // true
isAnyStringInside([1,2,3,4,5,2,3,4,5]); // false

相关问题