const quizData = [{
question: "Which of the following purpose, JavaScript is designed for ?",
a: 'To Execute Query Related to DB on Server',
b: 'To Style HTML Pages',
c: ' To Perform Server Side Scripting Opertion',
d: ' To add interactivity to HTML Pages.',
correct: 'd'
},
{
question: "how old is adnan?",
a: '10',
b: '20',
c: '30',
d: '40',
correct: 'c'
}]
以上是一个测验数据。我想只得到键的值在键'正确'值。像第一个问题一样,正确答案是'd',所以我只想得到键'd'的值。
我尝试了这个代码,但它给出了未定义的答案
let rs = quizData[0].correct
console.log(quizData[0].question + "n" + quizData[0].rs)
您可以使用这样的代码:
function getCorrectAnswerAtIndex(data, index) {
const item = data[index]
return item[item.correct]
}
用法:
// get answer at 0
console.log(quizData[0].question + 'n' + getCorrectAnswerAtIndex(0))
看起来你正在试图弄清楚如何访问一个对象的属性,当属性的名称存储在一个变量(而不是硬编码)
下面的3位代码都从myObj
得到相同的值:
myObj.myKey
或
myObj['myKey']
或
const myDynamicKey = 'myKey';
myObj[myDynamicKey]
所以在这种情况下,下面的代码应该对你有用:
const quizData = [{
question: "Which of the following purpose, JavaScript is designed for ?",
a: 'To Execute Query Related to DB on Server',
b: 'To Style HTML Pages',
c: ' To Perform Server Side Scripting Opertion',
d: ' To add interactivity to HTML Pages.',
correct: 'd'
}, {
question: "how old is adnan?",
a: '10',
b: '20',
c: '30',
d: '40',
correct: 'c'
}];
const correctLetter = quizData[0].correct;
console.log(quizData[0].question + "n" + quizData[0][correctLetter]);