繁体   English   中英

使用变量作为数组名

[英]Using a variable as array name

我有这样的数据结构:

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' ]
    }
  ]
}

我需要根据上下文进行导航和选择各种数据。 我需要bar1questions.bar[1].question可变。 我写了以下内容,但没有成功:

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]是因为questions[skill]是对该数组的引用,然后可以照常访问其元素。 因此,您只需执行以下操作即可提取问题文本:

'<p>' + baz.question + '</p>'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM