我在尝试迭代和添加动态数据时遇到了问题。以下是面临的例外情况:
Uncaught Error: Every row given must be either null or an array.
演示:https://plnkr.co/edit/vvY6Bg3uzVDSMwDh3EI6?p=preview
js code:
var list = [
{id:'January',min: 10, max:20, start:15,end:10},
{id:'Feb',min: 11, max:4, start:15,end:4},
{id:'March',min: 10, max:20, start:15,end:10},
{id:'APril',min: 5, max:20, start:55,end:10}
];
angular.forEach(list, function (value, key) {
// data.addRows([{"v":value.min}, {"v":value.max},{"v":value.start},{"v":value.end}]);
data.addRows([value.min,value.max,value.start,value.end]);
});
有关如何解决上述异常的任何输入?
答案 0 :(得分:1)
看起来每行有5列和4个值?
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Nescafe Instant');
data.addColumn('number', 'Folgers Instant');
data.addColumn('number', 'Nescafe Beans');
data.addColumn('number', 'Folgers Beans');
var list = [
{id:'January',min: 10, max:20, start:15,end:10},
{id:'Feb',min: 11, max:4, start:15,end:4},
{id:'March',min: 10, max:20, start:15,end:10},
{id:'APril',min: 5, max:20, start:55,end:10}
];
angular.forEach(list, function (value, key) {
var weekData = {};
// data.addRows([{"v":value.min}, {"v":value.max},{"v":value.start},{"v":value.end}]);
data.addRows([value.min,value.max,value.start,value.end]);
您是否需要为每行添加Topping
值?
this DataTable
example中的格式略有不同,但看起来原则相同。
修改强>:
期待一系列数组。你给它一个数组。有效的Here's a forked version:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Nescafe Instant');
data.addColumn('number', 'Folgers Instant');
data.addColumn('number', 'Nescafe Beans');
data.addColumn('number', 'Folgers Beans');
var list = [
{id:'January',min: 10, max:20, start:15,end:10},
{id:'Feb',min: 11, max:4, start:15,end:4},
{id:'March',min: 10, max:20, start:15,end:10},
{id:'APril',min: 5, max:20, start:55,end:10}
];
var allRows = [];
angular.forEach(list, function (value, key) {
var weekData = {};
allRows.push([value.id,value.min,value.max,value.start,value.end]);
// data.addRows([{"v":value.min}, {"v":value.max},{"v":value.start},{"v":value.end}]);
});
data.addRows(allRows);
答案 1 :(得分:1)
您需要将一个数组数组传递给addRows
,这样您就可以摆脱forEach。您可以使用map
将对象数组转换为数组数组。
您似乎还有5列,但只传入4个值。
固定代码是这样的:
var list = [
{id:'January',min: 10, max:20, start:15,end:10},
{id:'Feb',min: 11, max:4, start:15,end:4},
{id:'March',min: 10, max:20, start:15,end:10},
{id:'April',min: 5, max:20, start:55,end:10}
];
data.addRows(list.map(function(value) {
return [value.id,value.min,value.max,value.start,value.end];
}));
或者
data.addRows(list.map(value => [value.id,value.min,value.max,value.start,value.end]));