【问题标题】:How i can get array from loop for? [closed]我如何从循环中获取数组? [关闭]
【发布时间】:2020-09-18 11:22:58
【问题描述】:

大家好,可以帮我计算步数吗?enter image description here

function getPlan(currentProduction, months, percent) {
  // write code here
  let sum = 0;

  for(let i = 0; i < months; i++){
    let workCalculate = currentProduction * percent / 100;

    sum *= workCalculate;
  }
  return Math.floor(sum);
}

示例: getPlan(1000, 6, 30) === [1300, 1690, 2197, 2856, 3712, 4825] getPlan(500, 3, 50) === [750, 1125, 1687]

【问题讨论】:

  • 您将 0 与 x 相乘,它将始终为 0。
  • 我知道。但我可以知道如何通过步骤返回数组..
  • 我无法访问它之外的循环
  • 您的图像显示您期望一个具有六个整数的 array 作为结果,但您在代码中执行 return Math.floor(sum); - 这绝对不适合。
  • Decalre let sumArray=[] 然后推送元素。

标签: javascript loops


【解决方案1】:

只需将每次迭代推送到一个数组并返回该数组。

function getPlan(currentProduction, months, percent) {
  // write code here
  // starting at currentProduction
  let sum = currentProduction;
 
  // output
  let output = [];
  
  for(let i = 0; i < months; i++){
    // progressive from sum and not from currentProduction
    let workCalculate = sum * percent / 100;
  
    sum += Math.floor(workCalculate);
    output.push(sum)
  };
  
  return output
};

console.log(getPlan(1000, 6, 30))
console.log(getPlan(500, 3, 50))

【讨论】:

    【解决方案2】:

    目前您的方法返回一个数字,而不是一个数组。你到底需要什么?您需要它返回一个数组还是只想查看循环内完成的计算的中间值?

    在第一种情况下,创建一个空数组并在循环的每个步骤中添加您想要的值:

    function getPlan(currentProduction, months, percent) {
      // write code here
      let sum = 0;
      var result= [];
    
      for(let i = 0; i < months; i++){
        let workCalculate = currentProduction * percent / 100;
        sum *= workCalculate;
        result.push(sum);
      }
    
      return result;
    }
    

    在第二种情况下,您有两个选择:

    • 添加console.log,以便将值打印到控制台。
    • 添加一个breaking point,这样代码就停在它上面,您可以看到变量的值,并逐步执行程序。

    这有点模糊,因为您的需求不清楚,但希望对您有所帮助!

    【讨论】:

      【解决方案3】:

      function getPlan(currentProduction, months, percent) {
        var plan=[];
        var workCalculate=currentProduction;
        
        for(var i=0; i<months; i++) {
          workCalculate*=(1+percent/100);
          plan.push(Math.floor(workCalculate));
        }
        
        return plan;
      }
      
      console.log(getPlan(1000, 6, 30));
      console.log(getPlan(500, 3, 50));
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

      • floor() 似乎在错误的位置。您的实际输出与 4825 上的所需输出不匹配。
      • @Lain,感谢您的评论。 floor 在问题中,我会使用round4825 可能是问题中的错误,可能是我的。
      • @Lain,啊 - 这只是我没有删除的问题的复制粘贴。正在删除...
      • floor 提供更准确的进一步结果 - 特别是如果它是 round。使用round:在 100 上说 10%:110、121、133(.1)、146(.31)、161 NOT 160 (160.941),所以我保留 TRUE 累加器 (workCalculate ) 和 (将存储round,但在这里 - ) 存储每次迭代的floor。否决者:请辩解。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 2017-11-08
      • 2020-05-13
      • 1970-01-01
      相关资源
      最近更新 更多