我试图通过括号表示法访问其中一个对象属性,但我无法弄清楚它为什么不起作用。一如既往,非常感谢您的帮助!
JS:
var dude = [
{
question1: "What is dude's favourite food?",
choices1: ["Pizza", "Pasta", "Chips", "Ice cream"],
answer1: 1
},
{
question2: "What was dude's first ever job?",
choices2: ["Staples", "Vodafone", "Costa", "Post office"],
answer2: 0
},
]
var counter = 1;
var currentQues = "question"+counter;
console.log(dude[currentQues]);
控制台返回“undefined”。这是因为它无法通过变量(currentQues)访问属性,该变量基本上包含另一个变量(计数器)?
与往常一样,非常感谢您的帮助。我只是一个希望前进的初学者。
答案 0 :(得分:2)
dude
指的是对象的数组。您正试图访问question1
上的dude
,但您需要在dude[0]
上访问它:
console.log(dude[0][currentQues]);
// -------------^^^
直播示例:
var dude = [
{
question1: "What is dude's favourite food?",
choices1: ["Pizza", "Pasta", "Chips", "Ice cream"],
answer1: 1
},
{
question2: "What was dude's first ever job?",
choices2: ["Staples", "Vodafone", "Costa", "Post office"],
answer2: 0
},
]
var counter = 1;
var currentQues = "question"+counter;
console.log(dude[0][currentQues]);

我强烈建议您重新考虑该数据结构。所有对象的对象属性名称应该相同,只是它们在数组中的位置区分它们:
var dude = [{
question: "What is dude's favourite food?",
choices: ["Pizza", "Pasta", "Chips", "Ice cream"],
answer: 1
},
{
question: "What was dude's first ever job?",
choices: ["Staples", "Vodafone", "Costa", "Post office"],
answer: 0
},
]
dude.forEach(function(entry, index) {
var num = index + 1;
console.log("Question #" + num + ": " + entry.question);
});

答案 1 :(得分:1)
您还需要获取数组的索引。
var dude = [{ question1: "What is dude's favourite food?", choices1: ["Pizza", "Pasta", "Chips", "Ice cream"], answer1: 1 }, { question2: "What was dude's first ever job?", choices2: ["Staples", "Vodafone", "Costa", "Post office"], answer2: 0 }],
counter = 1;
currentQues = "question" + counter;
console.log(dude[counter - 1][currentQues]);
// ^^^^^^^^^^^