Javascript函数到列的总和(进入google dataTable)

时间:2014-04-09 13:12:45

标签: javascript jquery for-loop sum google-visualization

这里我有谷歌可视化数据表: enter image description here

我如何在这里添加新行和在postion [0]上将字符串“Sum”放在位置1中将为10,在位置[2]中将为17,作为列的总和... < / p>

我开始编写代码,但我不会去任何地方......

我试试:

data.addRow();
        for (var x=1, maxcol=data.getNumberOfColumns(); x < maxcol; x++) {
            for y=1, maxrow=data.getNumberOfRows(); y < maxrow; y++) {
        //WHAT NEXT ???

1 个答案:

答案 0 :(得分:1)

试试这个:

var group = google.visualization.data.group(data, [{
    type: 'number',
    column: 0,
    modifier: function () {return 0;}
}], [{
    type: 'number',
    column: 1,
    aggregation: google.visualization.data.sum
}, {
    type: 'number',
    column: 2,
    aggregation: google.visualization.data.sum
}]);

data.addRow(['Sum', group.getValue(0, 1), group.getValue(0, 2)]);

[编辑 - 添加代码以处理任意数量的列]

var groupColumns = [];
for (var i = 1; i < data.getNumberOfColumns(); i++) {
    groupColumns.push({
        type: 'number',
        column: i,
        aggregation: google.visualization.data.sum
    });
}

var group = google.visualization.data.group(data, [{
    type: 'number',
    column: 0,
    modifier: function () {return 0;}
}], groupColumns);

var row = ['Sum'];
for (var i = 1; i < group.getNumberOfColumns(); i++) {
     row.push(group.getValue(0, i));
}

data.addRow(row);