在javascript中存储在循环中派生的值

时间:2016-05-11 00:23:49

标签: javascript

我需要你帮忙。我想对将从循环中获得的值进行一些计算,但计算将取决于循环将计算的最后一个值。如何存储这些值,直到循环计算最后一个值,并使用结果对先前的值进行进一步计算。我需要一个演示示例

1 个答案:

答案 0 :(得分:-1)

我不确定你的意思,但你可以像这样存储循环中的每一个值:

//First, make an empty array.
var values = [];

//Then, make your loop. This loop runs 50 times, but
//you can make it run however many times you want.
for (var i = 0; i < 50; i++) {
  //This is where your loop does something with "i".
  //You can do whatever you want with it, but I've chosen to square it.
  values[i] = i * i;
}
//Now, "values" is an array with every calculation from the loop.
//Make another for loop, where "i" counts up to the length of "values".
for (var i = 0; i < values.length; i++) {
  //The last result of the first loop is values[values.length - 1].
  //here, do what you want with the values. I have chosen to divide each
  //value by the last calculation of the function.
  values[i] = values[i] / values[values.length - 1];
}

希望这会有所帮助。