【问题标题】:Using a variable as array name使用变量作为数组名
【发布时间】: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 中的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>'
  );
}

如果有人知道如何使数组名称本身成为变量,那将不胜感激。

【问题讨论】:

  • questions[skill].length 必须是 questions.skill.length(如果您确定 skillfoobar
  • @AlivetoDie 看起来根本不对。没有skill 属性
  • @phil 在他的代码中他创建了那个变量并在那里写到它就像 foo 或 bar 一样
  • @AlivetoDie 是的,但 questions.skill 未定义。正确的代码是questions[skill].length

标签: javascript jquery arrays variables


【解决方案1】:

以下应该可以解决问题;你只需要像往常一样拉取数组值:

var baz = questions[skill][i]; // will be `foo[i]` or `bar[i]`

这是有效的,因为questions[skill] 是对数组的引用,然后可以照常访问其元素。因此,您只需执行以下操作即可提取问题文本:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-25
    • 2012-05-08
    • 2011-01-11
    • 2023-03-27
    • 1970-01-01
    • 2011-12-30
    • 2012-05-09
    • 2013-06-21
    相关资源
    最近更新 更多