javascript - 使用变量作为数组名称

标签 javascript jquery arrays variables

我有一个像这样的数据结构:

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 中的 bar1 为变量。我写了以下内容但没有成功:

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/

相关文章:

javascript - Oracle Apex 从 ajax 请求中获取 cookie

javascript - 动态 jQuery 效果

JavaScript Focus() 位于带有 float 导航栏的元素 ID 上?

javascript - 制作动画并同时向 li 添加类

Javascript/JQuery 设置复选框的值,同时禁用其他复选框

java - 多维长度数组反射java

Javascript - 警告对象数组中的第一项?

javascript - 如何将 JSON 转换为数组并在 jQuery 中对其进行循环?

php - Javascript "window.location"停止 PHP 重定向

javascript - 如何防止过于频繁地执行 ajax 函数