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

问题描述 投票:0回答:1

数据对象中有一个对象,我将其写为对象,但是如果我进行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非常感谢您的帮助!

javascript arrays object
1个回答
0
投票

您比您想象的要深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 === []
© www.soinside.com 2019 - 2024. All rights reserved.