【问题标题】:Looping Parameters in JS FunctionsJS函数中的循环参数
【发布时间】:2017-08-11 11:54:02
【问题描述】:

我是 JS 编程的新手,想知道在函数中循环多个参数的最佳方法是什么。

作为一个例子,我想计算一个复利公式,它打印出具有一系列利率 (var y) 和不同投资时间范围 (var z) 的结果。

我可以让我的代码与一个循环一起工作(请参见下文),但不知道如何让它与两个变量一起工作(循环通过 x 和 y)。 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));
}

}

【问题讨论】:

  • 也许您从正确命名参数开始,例如资本、利率和年份
  • 请同时添加想要的结果。

标签: javascript function loops parameters


【解决方案1】:

在循环中描述你的变量

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
}

【讨论】:

    【解决方案2】:

    您可以使用两个嵌套的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; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      • 2014-05-20
      • 2021-02-09
      相关资源
      最近更新 更多