简体   繁体   English

如何使用另一个对象的属性值访问JavaScript对象的属性

[英]How to access properties of a JavaScript object using the property values of another object

Say I have these JavaScript objects: 假设我有以下JavaScript对象:

questions = { name: "Age", options:[boy, girl, daddy]}
answers = {"Age" : 21, "boy" : "checked", daddy : "checked"}

So if I wanted to access the "Age" from the answers object, I would do: 因此,如果我想从答案对象访问"Age" ,我将这样做:

x = answers.Age   //21

But how can I do the same thing but instead using the values from the questions object? 但是,除了使用问题对象中的值之外,我该如何做同样的事情?

x = answers.questions.name   //problem

or 要么

answers.questions.options[0]  //problem

As you can see I am trying to use the value of questions.name ( "Age" ) to access a property of answers ( Age ). 如您所见,我正在尝试使用questions.name"Age" )的值来访问答案的属性( Age )。

What's the right syntax or way? 什么是正确的语法或方式?

Try this: 尝试这个:

var x = answers[questions.name]

This works because: 之所以有效,是因为:

answers.Age

is equivalent to: 等效于:

answers['Age']

使用间接引用

answers[questions.name]

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

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