而不是被推到数组我得到错误

时间:2018-12-11 03:26:55

标签: javascript

我正在使用此预算应用程序。到目前为止,您的想法是在标记中选择一种类型(收入或费用),添加对该类型的描述,然后输入值。 (费用,买车,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);
    }
};
})();

1 个答案:

答案 0 :(得分:1)

  

输入值。 (费用,买车,2500),它应该推送到数据对象中的数组,相反,我在第30行不断出错。

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

但是expense中根本不存在data.allItems,如果我没记错的话,这将引发有关尝试访问.length中的undefined的错误。

因此,您可以将exp中的data.allItems键更改为expenses,或者将exp传递给addItem函数。

就代码可读性而言,在这种情况下使用expenses更合适。