数据对象中有一个对象,我将其写为对象,但是如果我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);
最佳答案
您对物体的了解比您想象的要深 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 === []
关于javascript - 我有一个应该是对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59202393/