2017-08-11 79 views
0

我是JS編程的新手,想知道什麼是循環函數內多個參數的最佳方法。JS函數中的循環參數

作爲一個例子,我想計算一個複合利息公式,用一系列利率(var y)和投資的不同時間範圍(var z)打印出結果。

我可以讓我的代碼與一個循環一起工作(請參見下文),但不能弄清楚如何使它能夠與兩個變量一起工作(循環遍歷x和y)。 ý應具有以下循環:

爲(Y = 0; Y> = 10; Y ++)

你能指向我入方向?

非常感謝。

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)); 
} 

} 
+4

也許你STA rt正確命名參數,如資本,利率和年 –

+0

請添加通緝令。 –

回答

0

您可以使用兩個嵌套的for循環和一個嵌套數組作爲結果。

結果看起來是這樣的:

[ 
    [    // 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; }

0

描述您的變量在循環

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 
}