简体   繁体   English

JS函数中的循环参数

[英]Looping Parameters in JS Functions

I am new to JS programming and wondered what the best way is to loop through multiple parameters inside a function. 我是JS编程的新手,我想知道最好的方法是在函数内部遍历多个参数。

As an example I would like to compute a compounded interest formula that prints out the results with a range of interest rates (var y) and different time horizons of an investment (var z). 例如,我想计算一个复利公式,该公式将打印出一系列利率(var y)和不同时间范围的投资(var z)的结果。

I could get my code to work with one loop (please see below) but don´t get the hang of how I could make it work with two variables (looping through x and y). 我可以使我的代码与一个循环一起工作(请参见下文),但不了解如何使我的代码与两个变量一起工作(通过x和y循环)。 Y should have the following loop: Y应该具有以下循环:

for ( y = 0; y >= 10; y++) 对于(y = 0; y> = 10; y ++)

Could you point me into the direction? 你能指出我的方向吗?

Much appreciated. 非常感激。

 var futureValue = function formula (x,y,z) {

 a = x * (Math.pow (1+y/100, z)); // where x is starting amount of money(principal), y is real interest rate in %, and z is the number of years for the investment
 return a;
 }
 for (z = 0; z <20; z++){
 console.log(futureValue (10000,5,z));
}

}

You could use two nested for loops and a nested array for the result. 您可以使用两个嵌套的for循环和一个嵌套的数组作为结果。

The result looks like this: 结果看起来像这样:

 [ [ // year zero with no interest "10000.00", "10000.00" // ... ], [ // year one with interest "10100.00", // with 1 % "10200.00", // with 2 % "10300.00", // with 3 % "10400.00", // with 4 % "10500.00", // with 5 % "10600.00", // with 6 % "10700.00", // with 7 % "10800.00", // with 8 % "10900.00" // with 9 % "11000.00", // with 10% ], [ // year two with interest "10201.00", "10404.00", // ... ], // ... ] 

 function futureValue(capital, interestRate, years) { return capital * Math.pow(1 + interestRate / 100, years); } var year, interestRate, temp, result = []; for (year = 0; year < 20; year++) { temp = []; for (interestRate = 1; interestRate <= 10; interestRate++) { temp.push(futureValue(10000, interestRate, year).toFixed(2)); } result.push(temp); } console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Describe your variables in a loop 循环描述您的变量

function formula (x,y,z) {
 a = x * (Math.pow (1+y/100, z)); // where x is starting amount of money(principal), y is real interest rate in %, and z is the number of years for the investment
 return a;
 }
 for (var z =0; z <20; z++){
 var x=1000;
 var y=5;
 console.log(formula(x,y,z));
 x++;//code for x on each iteration
 y++ // code for y
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM