我正在尝试填充条形图的数据集。我想将'dataset'添加到现有的barData1对象。
但我得到了以下错误。我在这做错了什么?
错误:jquery-3.1.1.min.js:2未捕获的TypeError:无法读取属性 'splice'未定义
<script type="text/javascript">
var jsprojStatList = @Html.Raw(ViewBag.projStatList);
$(document).ready(function () {
var barData1 = {
labels: ["No. Of Line Items", "Line Items Ordered", "( % )", "Line Items to be Ordered", "( % )", "PO Generated", "PO Approved", "PO Waiting for Approval"]
};
//var obj = JSON.parse(barData1);
//var parse_obj = JSON.parse(barData1);
var i = 0;
for (var key in jsprojStatList) {
if (jsprojStatList.hasOwnProperty(key)) {
var val = jsprojStatList[key];
barData1['datasets'].splice(i, 0, {
"label": val.BudgetTypeTitle, "backgroundColor": "rgba(220, 220, 220, 0.5)", "rgba(220, 220, 220, 0.5)": "#fff"
, "data": [val.NoOfBudgetItems, val.NoOfBudgetItemsOrdered, val.NoOfBudgetItemsOrderedPercentage, val.NoOfBudgetItemsToBeOrdered
, val.NoOfBudgetItemsToBeOrderedPercentage, val.POGenerated, val.POApproved, (val.POGenerated - val.POApproved)]
});
i++;
};
};
//}
var barOptions1 = {
responsive: true
};
var ctx21 = document.getElementById("barChart1").getContext("2d");
new Chart(ctx21, { type: 'bar', data: barData1, options: barOptions1
});
</script>
答案 0 :(得分:1)
在为其添加值之前,您必须将barData1['datasets']
本身定义为数组:
var barData1 = {
datasets: [], // populated below
labels: ["No. Of Line Items", "Line Items Ordered", "( % )", "Line Items to be Ordered", "( % )", "PO Generated", "PO Approved", "PO Waiting for Approval"]
};
第一次使用时, .splice()
不会/不能自动为您创建数组。
附注:
由于您似乎没有将i
用于其他任何内容,因此可以使用.push(value)
代替.splice(i, 0, value)
。这样您就可以放弃var i = 0
和i++
。
如果jsprojStatList
是Array
(从名称List
开始猜测),a for..in
loop isn't usually appropriate with them。