javascript - 在输出之前随机化 JSON 内容的内容

标签 javascript jquery arrays json

公平警告,您可能会对下面的代码感到畏缩,但我正在尽我所知。

我有一个包含几个问题的 JSON 文件,其内容如下:

{
    "questions": [
        {
            "id": 1,
            "question": "What is 2+2?",
            "answers": [
                {
                    "answer": "1"
                },
                {
                    "answer": "6"
                },
                {
                    "answer": "4"
                }
          ],
          "answer": 3
        },
        {
            "id": 2,
            "question": "What is a dog?",
            "answers": [
                {
                    "answer": "animal"
                },
                {
                    "answer": "object"
                }
          ],
          "answer": 1
        }
    ]
}

我正在获取此内容并将其显示为 slider 内的测验。为此,我使用以下内容:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>title</title>
  <link rel="stylesheet" href="stylesheet.css" type="text/css">
  <link rel="stylesheet" href="slick/slick.css" type="text/css">
  <link rel="stylesheet" href="slick/slick-theme.css" type="text/css">
  <style type="text/css">
.answerCorrect {
    color:green;
}
.answerIncorrect {
    color:red;
}
  </style>
  </head>
  <body>

    <div id="quizPage">
        <div id="quizSlider"></div>
    </div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
    <script src="slick/slick.js" type="text/javascript"></script>

    <script>
            // Start the question slider


            $.getJSON("quiz.json", function(data) {
                var html = '';
                console.log(data.questions);
                $.each(data.questions, function(key, value){
                    correctAnswer = value.answer;
                    html += '<div id="'+value.id+'" class="quizItem">';
                    html += '<div class="quizQuestion">'+value.question+'</div>';

                    $.each(value.answers, function(index, question) {
                        answerIndex = index+1;
                        if(answerIndex == correctAnswer) { answerValidation = 'true'; } else { answerValidation = 'false'; }
                        html += '<div data-answerValidation="'+answerValidation+'" data-answerIndex="'+answerIndex+'" class="quizAnswer">'+question.answer+'</div>';
                    });
                    html += '</div>';
                });
                $('#quizSlider').html(html);
                $('#quizSlider').slick();
            });

            $("#quizSlider").on( 'click', '.quizAnswer', function () {
                validation = $( this ).attr( "data-answerValidation" );
                console.log(validation);
                if ($( this ).attr( "data-answerValidation" ) === 'true') {
                    $( this ).addClass('answerCorrect');
                } else {
                    $( this ).addClass('answerIncorrect');
                    $( this ).siblings('[data-answerValidation="true"]').addClass('answerCorrect');
                }
                setTimeout(function(){ $('#quizSlider').slick('slickNext'); }, 1000);

            });
    </script>
  </body>
</html>

我需要做的是随机化用户每次访问页面时向其显示问题的顺序。我见过获取单个随机项但不随机化整个列表的方法。

最佳答案

在运行每个循环之前:

$.each(data.questions, function(key, value){

您可以对 data.questions 数组进行洗牌,如下所示:

function ShuffleQuestions(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

然后像这样使用它:

ShuffleQuestions(data.questions);
$.each(data.questions, function(key, value){

演示:

function ShuffleQuestions(array) {
  var currentIndex = array.length,
    temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

let questions = [
  { "id": 1, "question": "What is 2+2?" },
  { "id": 2, "question": "What is a dog?" },
  { "id": 3, "question": "What is 1+1?" },
];
ShuffleQuestions(questions);
console.log(questions);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 在输出之前随机化 JSON 内容的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60545035/

相关文章:

javascript - 用js获取html源码相关的选中html元素偏移量

javascript - 如何在sightly JAVA Script USE API中将对话框属性值传递给AJAX请求?

javascript - 表单标签过早关闭

javascript - Chrome 中可以使用书签吗?

javascript - 在时间跨度内收集键盘输入

javascript - 放置在表格单元格边框上时未触发放置事件

jquery - 在 Bootstrap 汉堡包按钮内垂直居中文本

c - 将csv文件读入c中的二维数组

java - 创建一副具有两种变化的纸牌 : 52 and infinite

Java数组逆序排序!需要反向反转