我有一个像这样的数据结构:
var questions {
'foo' : [
{
'question' : 'Where do babies come from?',
'choice' : [ 'a', 'b', 'c', 'd' ]
},
{
'question' : 'What is the meaning of life?',
'choice' : [ 'a', 'b', 'c', 'd' ]
}
],
'bar' : [
{
'question' : 'Where do babies come from?',
'choice' : [ 'a', 'b', 'c', 'd' ]
},
{
'question' : 'What is the meaning of life?',
'choice' : [ 'a', 'b', 'c', 'd' ]
}
]
}
我需要根据上下文导航和选择各种数据。我需要 questions.bar[1].question
中的 bar
和 1
为变量。我写了以下内容但没有成功:
var quiz = $('[id*="Quiz"]');
var skill = quiz.attr('id').substring(0, 3); // 'foo' or 'bar'
var string = '';
for(var i = 0; i < questions[skill].length; i++) {
var baz = skill + '[' + i + ']'; // need to produce 'foo[0]' or 'bar[0]'
string += (
'<div>' +
'<p>' + questions[baz].question + '</p>' // need to select questions.foo[0].question or questions.bar[0] and then print '<p>Where do babies come from?</p>'
);
}
如果有人知道如何使数组名称本身成为一个变量,我们将不胜感激。
最佳答案
以下应该可以解决问题;您只需像平常一样提取数组值即可:
var baz = questions[skill][i]; // will be `foo[i]` or `bar[i]`
这是有效的,因为questions[skill]
是对数组的引用,然后可以照常访问其元素。因此,您只需执行以下操作即可提取问题文本:
'<p>' + baz.question + '</p>'
关于javascript - 使用变量作为数组名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48257262/