Ricardo de Vries Ricardo de Vries - 2 months ago 7
jQuery Question

Counting in jquery Array

I seem to have trouble calculating some numbers together. When I want to use:

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


I am getting a
NaN
and thereforce every group has a
NaN
. Is this the right way of even using
week_total[group] = week_total[group] + work_minutes;
?

My script:

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

Answer

I think, problem is in not initialized week_total array.

Calculating should be like

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

If week_total[group] is undefined then week_total[group] + 1 will be NaN