gpt4 book ai didi

javascript - 我有一个应该是对象的数组

转载 作者:行者123 更新时间:2023-12-02 22:21:53 25 4
gpt4 key购买 nike

数据对象中有一个对象,我将其写为对象,但是如果我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);

Here is the console.log with the array非常感谢您的帮助!

最佳答案

您对物体的了解比您想象的要深 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com