在jquery数组中计数

时间:2016-09-13 12:59:53

标签: javascript jquery datatables

我似乎无法一起计算一些数字。当我想使用时:

for (var key in week_total) {
    $("." + key).html(week_total[key]);
}

我得到NaN,每个小组都有一个NaN。这是使用week_total[group] = week_total[group] + work_minutes;的正确方法吗?

我的剧本:

drawCallback: function (settings) {
    var api   = this.api(), data;
    var rows  = api.rows({page: 'current'}).nodes();
    var last  = null;

    var week_total = new Array;

    api.column(weekColumn, { page: 'current' }).data().each(function (group, i) {
        var work_hours   = api.column(hourColumn).data()[i].split(':');
        var work_minutes = (+ work_hours[0]) * 60 + (+ work_hours[1]);

        week_total[group] = week_total[group] + work_minutes;

        if (last !== group) {
            $(rows).eq(i).before('<tr><td colspan="5">{{ trans('admin.worktime.field.week') }} ' + group + '</td><td colspan="3" style="font-style:italic;" class="' + group + '"></td></tr>');

            last = group;
        }
    });

    for (var key in week_total) {
        $("." + key).html(week_total[key]);
    }

    var array = {
        work_month: work_month,
        work_year: work_year
    };

    history.pushState(null, null, '?' + $.param(array));

    drawDataTable(this);
}

1 个答案:

答案 0 :(得分:0)

我认为,问题是未初始化的week_total数组。

计算应该像

week_total[group] = week_total[group]
    ? week_total[group] + work_minutes
    : work_minutes;

如果未定义week_total [group],则week_total [group] + 1将为NaN