我正在尝试构建一个预算应用程序,但出现错误
无法读取未定义的属性'length'
在Object.addItem(app.js:36)
在HTMLButtonElement.ctrlAddItem(app.js:128)
这是我的代码:
// DATA Module
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;
// create new ID
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
//create new item based on 'inc' or 'exp' type
if(type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}
// push it into our data structure
data.allItems[type].push(newItem);
// return the new element
return newItem;
},
testing: function() {
console.log(data)
}
};
})();
var data = {
allItems: {
exp: [1,2,3],
inc: []
},
totals: {
exp: 0,
inc: 0
}
};
// UI module
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 , // will be either inc or exp
description: document.querySelector(DOMstrings.inputDescription).value ,
value: document.querySelector(DOMstrings.inputValue).value
};
},
getDOMstrings: function() {
return DOMstrings;
}
};
})();
// GLOPAL APP CONTROLLER
var controller = (function(budgetCtrl, UICtrl) {
var setupEvenetListeners = 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;
// 1. get the field input data
input = UICtrl.getInput();
// 2. add the item to the budget controller
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
// 3. add the new item to the UI
// 4. calculate the budget
// 5. display the budget on the UI
}
return {
init: function() {
setupEvenetListeners();
}
};
})(budgetController, UIController);
controller.init();
我确定那里的错误,但过去两个小时来了,我在这里找不到它:
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
这应该从输入字段中获取数据,然后为每个输入数据创建唯一的ID,然后将其推送到data.allItems ['exp'或'inc']