数据对象中有一个对象,我将该对象写为对象,但是如果我用console.log记录它,浏览器会说它是一个数组。但是我清楚地给了它对象括号。我正在观看的教程也可以像数组一样使用它。该代码工作正常,但没有答案我无法入睡。
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: { //Here is the object
exp: [],
inc: [],
},
totals: {
exp: 0,
inc: 0,
},
};
return {
addItem: function(type, des, val){
var newItem, ID;
//ID = last ID + 1
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
if (type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}
console.log(data.allItems[type]);
data.allItems[type].push(newItem);
return newItem;
},
};
})();
budgetController.addItem('inc', 'test', 22);
答案 0 :(得分:1)
您比您想象的要深1级。有问题的打印数组的代码是console.log(data.allItems[type])
。根据您的函数调用,type === 'inc'
。
data === {
allItems: {
exp: [],
inc: [],
},
totals: {
exp: 0,
inc: 0,
},
};
data.allItems === {
exp: [],
inc: [],
},
最后,您实际上正在打印的难题之所在:
data.allItems['inc'] === data.allItems.inc === []