我正在研究这个预算应用程序。现在的想法是在标记中选择一种类型(收入或支出),添加所述类型的描述,然后输入值。 (费用,买车,2500)它应该推送到数据对象中的数组,而不是我在第30行得到错误。(错误在线评论)
// BUDGET CONTROLLER
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;
//[1 2 3 4 5], next ID = 6
//[1 2 4 6 8], next ID = 9
// ID = last ID + 1
// Create new ID
if (data.allItems[type].length > 0){ //ERROR THROWN HERE
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);
}
};
})();
输入值。 (费用,买车,2500)它应该推送到数据对象中的数组,而不是我继续获取和第30行的错误。
原因是你将expense
作为addItem
函数的第一个参数传递,用于访问data.allItems
。
然而expense
在data.allItems
中根本不存在,如果我没有弄错的话,将会尝试访问.length
的undefined
。
因此,要么将exp
中的data.allItems
键更改为expenses
,要么将exp
更改为addItem
函数。
在代码可读性方面,使用expenses
更适合这种情况。