而不是被推到阵列我得到错误

问题描述 投票:0回答:1

我正在研究这个预算应用程序。现在的想法是在标记中选择一种类型(收入或支出),添加所述类型的描述,然后输入值。 (费用,买车,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);
    }
};
})();
javascript
1个回答
1
投票

输入值。 (费用,买车,2500)它应该推送到数据对象中的数组,而不是我继续获取和第30行的错误。

原因是你将expense作为addItem函数的第一个参数传递,用于访问data.allItems

然而expensedata.allItems中根本不存在,如果我没有弄错的话,将会尝试访问.lengthundefined

因此,要么将exp中的data.allItems键更改为expenses,要么将exp更改为addItem函数。

在代码可读性方面,使用expenses更适合这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.