使用 "months" 数组在 for 循环中为每个月执行计算

Use a "months" array to perform calculations for each month in a for loop

我有一个 mongo 集合来存储 "projects",每个文档存储一个项目,一年中的每个月都有不同的计算

a_jan : 10,
a_feb : 20,
a_mar : 25,
a_apr : 70
...

b_jan : 30,
b_feb : 10,
b_mar : 20,
b_apr : 70
...

c_jan : 80,
c_feb : 2,
c_mar : 20,
c_apr : 65
...

我创建了一个模板助手来执行一些数学计算,涉及每个月的字段(即:rtwc_jan = (a_jan + b_jan) / c_jan)。

有很多不同的计算,但每个月都执行相同的计算。

如何使用 for 循环来容纳来自 "months" 数组的数组 key

这是我的代码(w/o for 循环...)

var months = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","des"];

var arrayLength = months.length;

for (var i = 0; i < arrayLength; i++) {
        alert(months[i]);       

        // Need to Calculate rtcw for each month        

        var scope = {
                a_jan : currentProject.a_jan,
                b_jan : currentProject.b_jan,
                c_jan : currentProject.c_jan,
        };      

        var calculation_a = math.eval('(a_jan - b_jan) * c_jan / 35', scope);

        scope.a = calculation_a;

        var rtcw_jan = math.eval('max(a,15)', scope);

        console.log(rtcw_jan);
}

我认为您想通过使用月份作为键从 currentProject 对象中获取属性。像这样:

var months = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","des"];
var arrayLength = months.length;
var rtcw = {};

for (var i = 0; i < arrayLength; i++) {
        alert(months[i]);

        // Need to Calculate rtcw for each month
        var scope = {
                a : currentProject["a_" + months[i]],
                b : currentProject["b_" + months[i]],
                c : currentProject["c_" + months[i]],
        };

        var calculation_a = math.eval('(a - b) * c / 35', scope);

        scope.a = calculation_a;

        rtcw[months[i]] = math.eval('max(a,15)', scope);
        console.log(rtcw[months[i]]);
}

简化版:

var months = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","des"];
var rtcw = {};

for (var i = 0; i < months.length; i++) 
{
    var a = currentProject["a_" + months[i]];
    var b = currentProject["b_" + months[i]];
    var c = currentProject["c_" + months[i]];

    rtcw[months[i]] = max((a - b) * c / 35, 15);

    console.log(rtcw[months[i]]);
}