javascript - 我有一个应该是对象的数组
问题描述
数据对象中有一个对象,我把它写成一个对象,但是如果我 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);
解决方案
你比你想象的要深一层。有问题的打印数组的代码是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 === []
推荐阅读
- pytorch - 用 CPU 加载 pickle 保存的 GPU 张量?
- python - 尝试导入 python-vlc 时出现错误
- arrays - 程序应该崩溃,但它没有
- kubernetes - 如何从外部访问 pod IP
- c# - 如何代表流创建以从 Web Chat 生成用于 Bot 身份验证的访问令牌?
- javascript - 通过数组过滤包含对象数组的对象数组
- javascript - Angularjs指令使HTML元素可拖动并且其中的HTML字段可选择或可修改
- python - 在python中分块下载文件?
- dataframe - 如果一个数据帧依赖于另一个数据帧,火花数据帧执行如何工作?
- git - 如何在 Redmine 中获得修订和 git 问题链接?