繁体   English   中英

如何使用方括号表示法使用多个变量来调用嵌套对象?

[英]How do I use Square Bracket Notation to use multiple variables to call nested objects?

我正在尝试创建一个函数,该函数将使用多个变量来选择正确的嵌套对象,然后对其进行操作。

var group1 = {
        fred: {
            debt: 5,
            income: 2
        },
        suzy: {
            debt: 3,
            income: 5
        }
    },
    group2 = {
        molly: {
            debt: 4,
            income: 4
        },
        jason: {
            debt: 6,
            income: 1
        }
    };

function debtCheck(group, name) {
    console.log(group.name.debt);         ==>Uncaught TypeError: Cannot read property 'debt' of undefined
    console.log(group[name].debt);        ==>Uncaught TypeError: Cannot read property 'debt' of undefined
    console.log([group][name].debt);      ==>Uncaught TypeError: Cannot read property 'debt' of undefined
    console.log([group[name]].debt);      ==>undefined
}

debtCheck('group1', 'fred');

目标是使它在控制台中显示5。 如果我只做一个变量,它就可以正常工作。

function debtCheck(name) {
    console.log(group1[name].debt);
}

debtCheck('fred');

希望我能清楚说明我的要求。 谢谢您的帮助!

我对此有其他想法:基础对象不能是变量吗? 还是不能连续有两个变量?

您将第一个参数作为字符串而不是对象传递。 尝试debtCheck(group1, 'fred'); 同样,由于第二个参数应该是一个字符串,因此您需要通过group[name].debt访问它。

关于第一点的一些背景材料可以帮助您: 将值/引用传递给函数 关于第二点: 使用对象

 var group1 = { fred: { debt: 5, income: 2 }, suzy: { debt: 3, income: 5 } }; var group2 = { molly: { debt: 4, income: 4 }, jason: { debt: 6, income: 1 } }; function debtCheck(group, name) { console.log(group[name].debt); } // debtCheck('group1', 'fred'); debtCheck(group1, 'fred'); 

两件事情。 您将group1作为字符串而不是对象放入。 其次,在通过特定变量名称引用对象时,不能使用点符号。 您需要使用方括号。

尝试:

function debtCheck(group, name) {
    console.log(group[name].debt);
 }

debtCheck(group1, 'fred');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM