猿问

我如何从循环中获取数组?

大家好,你能帮我计算步数吗?在此处输入图像描述

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]


RISEBY
浏览 111回答 3
3回答

隔江千里

只需将每次迭代推送到一个数组并返回该数组。function getPlan(currentProduction, months, percent) {&nbsp; // write code here&nbsp; // starting at currentProduction&nbsp; let sum = currentProduction;&nbsp;&nbsp; // output&nbsp; let output = [];&nbsp;&nbsp;&nbsp; for(let i = 0; i < months; i++){&nbsp; &nbsp; // progressive from sum and not from currentProduction&nbsp; &nbsp; let workCalculate = sum * percent / 100;&nbsp;&nbsp;&nbsp; &nbsp; sum += Math.floor(workCalculate);&nbsp; &nbsp; output.push(sum)&nbsp; };&nbsp;&nbsp;&nbsp; return output};console.log(getPlan(1000, 6, 30))console.log(getPlan(500, 3, 50))

慕慕森

目前你的方法返回一个数字,而不是一个数组。你到底需要什么?您需要它返回一个数组,还是只想查看循环内计算的中间值?在第一种情况下,创建一个空数组并在循环的每一步中添加您想要的值:function getPlan(currentProduction, months, percent) {&nbsp; // write code here&nbsp; let sum = 0;&nbsp; var result= [];&nbsp; for(let i = 0; i < months; i++){&nbsp; &nbsp; let workCalculate = currentProduction * percent / 100;&nbsp; &nbsp; sum *= workCalculate;&nbsp; &nbsp; result.push(sum);&nbsp; }&nbsp; return result;}在第二种情况下,您有两个选择:添加一个console.log,以便将值打印到控制台。添加一个断点,以便代码在该处停止,您可以看到变量的值并逐步执行程序。这有点含糊,因为您的需求不清楚,希望对您有所帮助!

森栏

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

相关分类

JavaScript
我要回答