I'm trying to create a budget controller.
When I try to push an item into an array, I get this error:
Uncaught TypeError: Cannot read property 'length' of undefined
The error is on line 33, which begins:
if(data.allItems[type].length >0){ What's going wrong?
Here's the complete code:
var budgetController = (function(){ //function constructor 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 off of inc or exp type if(type === 'exp'){ newItem = new Expense(ID, des, val); } else if(type === 'inc'){ newItem = new Income(ID, des, val); } //push onto data structure data.allItems[type].push(newItem); //return the new element return newItem; }, testing: function(){ console.log(data); } }; })();
data.allItems[type]isundefined, not an array like you expect. To figure out why, use the tips from this article to figure out what is going on. Specifically, you should addconsole.log(type)andconsole.log(data.allItems[type])to see their values.