使用变量作为数组名称

时间:2022-08-09 23:51:14

I have a data structure like so:

我有这样的数据结构:

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

I need to navigate and select various data contextually. I need bar and 1 in questions.bar[1].question to be variable. I have written the following and have had no success:

我需要在上下文中导航和选择各种数据。我在问题中需要bar和1.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>'
  );
}

If anyone knows how to make the array name itself a variable, that would be much appreciated.

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

1 个解决方案

#1


7  

The following should do the trick; you just need to pull the array value as you normally would:

以下应该做的伎俩;你只需像往常一样拉出数组值:

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

This works because questions[skill] is a reference to the array, whose elements can then be accessed as usual. So then you would simply do the following to pull the question text:

这是有效的,因为问题[技巧]是对数组的引用,然后可以像往常一样访问其元素。那么你只需要执行以下操作来提取问题文本:

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

#1


7  

The following should do the trick; you just need to pull the array value as you normally would:

以下应该做的伎俩;你只需像往常一样拉出数组值:

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

This works because questions[skill] is a reference to the array, whose elements can then be accessed as usual. So then you would simply do the following to pull the question text:

这是有效的,因为问题[技巧]是对数组的引用,然后可以像往常一样访问其元素。那么你只需要执行以下操作来提取问题文本:

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