[英]How to access properties of a JavaScript object using the property values of another object
假設我有以下JavaScript對象:
questions = { name: "Age", options:[boy, girl, daddy]}
answers = {"Age" : 21, "boy" : "checked", daddy : "checked"}
因此,如果我想從答案對象訪問"Age"
,我將這樣做:
x = answers.Age //21
但是,除了使用問題對象中的值之外,我該如何做同樣的事情?
x = answers.questions.name //problem
要么
answers.questions.options[0] //problem
如您所見,我正在嘗試使用questions.name
( "Age"
)的值來訪問答案的屬性( Age
)。
什么是正確的語法或方式?
嘗試這個:
var x = answers[questions.name]
之所以有效,是因為:
answers.Age
等效於:
answers['Age']
使用間接引用
answers[questions.name]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.