未捕获TypeError:无法读取未定义的属性'addItems'
问题描述:
我正尝试使用jqplot创建饼图,但出现标题中显示的错误。最终,我想使用下面的代码来创建不同类型的jqplot图表,因为数据格式基本相同。在的for循环retrieveData()是我将创建数据,将填充将生成饼图或条形图的所有项目数组。我想先让它为饼图工作。您还可以找到https://jsfiddle.net/isogunro/5peuchqe/未捕获TypeError:无法读取未定义的属性'addItems'
var schoolApp = window.schoolApp || {};
schoolApp.itemType = new Array();
$(document).ready(function() {
retrieveData();
});
function retrieveData() {
var allItems = new getItems();
var k=0;
for (i=0; i<10; i++){
k +=i;
window.allItems.addItems("Hello"+i, k);
}
chartArray = window.allItems.getChartData();
plotChart(chartArray);
}
function getItems() {
this.inputs = {};
this.items = [];
this.addItems = function (unqItem, amount1) {
if (!this.inputs[unqItem]) {
this.items.push(unqItem);
this.inputs[unqItem] = 0;
}
this.inputs[unqItem] += amount1;
};
this.getChartData = function() {
var chartAry = [];
for (i = 0; i < this.items.length; ++i) {
chartAry.push([this.items[i], this.inputs[this.items[i]]]);
}
return chartAry;
}
} // end of function truck2pie
function plotChart(data) {
var plot1 = jQuery.jqplot('pieChart', [data],
{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
fill: true,
sliceMargin: 7,
dataLabels: 'value', //Show data instead of label
showDataLabels: true,
linewidth: 5,
shadowOffset: 2,
shadowDepth: 5, //Number of strokes to make when drawing shadow. Each stroke offset by shadowOfset from the last.
shadowAlpha: 0.07
}
},
legend: { show: true, location: 'e' }
}
);
}
答
你不使用window
访问一个局部变量,只是将其删除,它会工作。
function retrieveData() {
var allItems = new getItems();
var k=0;
for (i=0; i<10; i++){
k +=i;
allItems.addItems("Hello"+i, k);
}
chartArray = allItems.getChartData();
plotChart(chartArray);
}
function getItems() {
this.inputs = {};
this.items = [];
this.addItems = function (unqItem, amount1) {
if (!this.inputs[unqItem]) {
this.items.push(unqItem);
this.inputs[unqItem] = 0;
}
this.inputs[unqItem] += amount1;
};
this.getChartData = function() {
var chartAry = [];
for (i = 0; i < this.items.length; ++i) {
chartAry.push([this.items[i], this.inputs[this.items[i]]]);
}
return chartAry;
}
}
的错误是很清楚的,your're试图访问一个不存在的属性:'window.allItems'是不确定的,所以你不能。 – DCruz22
[检测未定义对象属性]的可能重复(http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property) –