如何在数组中随机排列数组?

How do I shuffle an array within an array?

设置说明: 我正在构建一个带有微调器的问答游戏。此微调器分为 6 个类别(第 6 个类别是所有前 5 个类别的组合)。前 5 个类别将有自己的一组问题。一旦微调器停在某个类别上,就会出现一个表格,该表格将根据其类别按顺序提出一系列问题。每个问题有 3 个选择,其中 1 个是正确的选择。

下面是一个简短的问题库数组来说明我的想法: ```

var questionBankArray = 
 [{
    category: "Category1",
    question: "What does the following expression return? <br> 3 / 'bob';",
    choices: ["undefined", "ReferenceError", "NaN"],
    correctAnswer: "NaN"
   },{
     category: "Category1"
     question: "What is a method?",
     choices: ["Used to describe an object.", "A function assigned to an object.", "Performs a function on one or more operands or variables."],
     correctAnswer: "A function assigned to an object."
   },{
     category: "Category2"
     question: "Which company first implemented the JavaScript language?",
     choices: ["Netscape Communications Corp.", "Microsoft Corp.", " Sun Microsystems Corp."],
     correctAnswer: "Netscape Communications Corp."
    },{
     category: "Category2"
     question: "When was the first release of a browser supporting JavaScript?",
     choices: ["1996", "1995", " 1994"],
     correctAnswer: "1995"
    },
 ];

```

我想遍历对象的 questionBanArray,并按类别在该类别内随机播放。我还希望能够在该类别的每个问题中随机选择选项。我该怎么做?重写它看起来像这样会不会更容易:

questionBankArray = 
[{
  CategoryBank1: 
    [{
        question1: "What is blank?", 
        choices: ["choice1","choice2","answer"], 
        answer: "answer"
        },{
        question2: "What is blank?", 
        choices: ["choice1","choice2","answer"], 
        answer: "answer"
     }],
   CategoryBank2: 
     [{
        question1: "What is blank?", 
        choices: ["choice1","choice2","answer"], 
        answer: "answer"
        },{
        question2: "What is blank?", 
        choices: ["choice1","choice2","answer"], 
        answer: "answer"
      }]
 }];

我认为理想的结构应该是这样的:

questionBankArray = 
  [{
    category:"first category",
    questions: 
      [{
        question1: "What is blank?", 
        choices: ["choice1","choice2","answer"], 
        answer: "answer"
      },{
        question2: "What is blank?", 
        choices: ["choice1","choice2","answer"], 
        answer: "answer"
      }]
  },
  {
    category: "second category",
    questions:
      [{
        question1: "What is blank?", 
        choices: ["choice1","choice2","answer"], 
        answer: "answer"
      },{
        question2: "What is blank?", 
        choices: ["choice1","choice2","answer"], 
        answer: "answer"
      }]
    }];

创建随机播放函数:

function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

开始循环你的外层数组,越来越深,从最内层到外层数组应用随机播放函数

for (var category in questionBankArray) {
  for (var question in category.questions) {
    shuffle(question.choices);
  }
  shuffle(category);
}
shuffle(questionBankArray);