我知道有人问我这个问题。但我不知道为什么我还是会犯这个错误。
Ucaught TypeError: Cannot read property 'length' of undefined
at Object.addItem
我不知道长度是如何定义的,当我检查它是否大于0时,我是否没有访问
data
对象是否正确?
addItem
功能。在这个函数中,我在这行得到一个错误:
if (data.allItems[type].length > 0) {
这是全部功能。
var budgetController = (function() {
var Expense = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
};
var Income = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
};
var data = {
allItems: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
}
};
return {
addItem: function(type, des, val) {
var newItem, ID;
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
if (type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}
data.allItems[type].push(newItem);
return newItem;
},
testing: function() {
console.log(data);
}
}
})();
我也叫它这里。
var ctrlAddItem = function() {
var input, newItem;
input = UICtrl.getinput();
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
}
用户界面控制器-我在那里得到输入。
var UIController = (function() {
var DOMstrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn'
}
return {
getinput: function() {
return {
type: document.querySelector(DOMstrings.inputType).value,
description: document.querySelector(DOMstrings.inputDescription).value,
value: document.querySelector(DOMstrings.inputValue).value
}
},
getDOMstrings: function() {
return DOMstrings;
}
}
})();
var controller = (function(budgetCtrl, UICtrl) {
var setupEventListerners = function() {
var DOM = UICtrl.getDOMstrings();
document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);
document.addEventListener('keypress', function(event) {
if(event.keyCode == 13 || event.which == 13) {
ctrlAddItem();
}
});
};
var ctrlAddItem = function() {
var input, newItem;
input = UICtrl.getinput();
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
}
return {
init: function() {
console.log('application start');
setupEventListerners();
}
}
})(budgetController, UIController);
controller.init();
有什么想法吗?