【发布时间】:2018-06-23 17:54:04
【问题描述】:
我有一个像这样的数据结构:
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>'
);
}
如果有人知道如何使数组名称本身成为变量,那将不胜感激。
【问题讨论】:
-
questions[skill].length必须是questions.skill.length(如果您确定skill是foo或bar) -
@AlivetoDie 看起来根本不对。没有
skill属性 -
@phil 在他的代码中他创建了那个变量并在那里写到它就像 foo 或 bar 一样
-
@AlivetoDie 是的,但
questions.skill未定义。正确的代码是questions[skill].length
标签: javascript jquery arrays variables