使用“months”数组在for循环中执行每个月的计算

时间:2015-06-15 17:08:26

标签: javascript arrays meteor meteor-helper

我有一个用于存储“项目”的mongo集合,每个文档存储一个项目,该项目在一年中的每个月都有不同的计算

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循环来容纳来自“月”数组的数组key

这是我的代码(没有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);
}

1 个答案:

答案 0 :(得分:0)

我认为您希望通过将月份作为键来获取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]]);
}