我正在尝试进行数据可视化,我需要知道如何对每个月的所有值求和,还有JSON数据:
var data = [
{
"created_at": "2016-01-06",
"commission": "238.00"
},
{
"created_at": "2016-01-12",
"commission": "538.00"
},
{
"created_at": "2016-02-02",
"commission": "12.00"
},
{
"created_at": "2016-03-06",
"commission": "113.00"
},
{
"created_at": "2016-03-18",
"commission": "212.00"
}
];
这是每月汇总所有委托价值的算法:
var months = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var date;
for (var i = 0; i < data.length; i++) {
date = new Date(data[i].created_at);
if (date.getFullYear() == 2016) {
months = months[date.getMonth()] += +data[i].commission;
}
}
//excepted result would be [776, 12, 325, 0, 0, 0, 0, 0, 0, 0, 0, 0]
alert(months);
我无法弄清楚这个逻辑,它返回了第一个委托或NaN索引。例外结果将是每月添加值的数组,如下所示:[776,12,325,0,0,0,0,0,0,0,0]
有JSfiddle https://jsfiddle.net/md57g0qq/1/
答案 0 :(得分:1)
你有一个错字。将months = months[date.getMonth()] += +data[i].commission;
更改为months[date.getMonth()] += +data[i].commission;
答案 1 :(得分:0)
var data = [
{
"created_at": "2016-01-06",
"commission": "238.00"
},
{
"created_at": "2016-01-12",
"commission": "538.00"
},
{
"created_at": "2016-02-02",
"commission": "12.00"
},
{
"created_at": "2016-03-06",
"commission": "113.00"
},
{
"created_at": "2016-03-18",
"commission": "212.00"
}
];
var months = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var date;
for (var i = 0; i < data.length; i++) {
date = new Date(data[i].created_at);
if (date.getFullYear() == 2016) {
months[date.getMonth()] = parseFloat(months[date.getMonth()]) + parseFloat( data[i].commission);
}
}
//excepted result would be [776, 12, 325, 0, 0, 0, 0, 0, 0, 0, 0, 0]
alert(months);