首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript随机数组,不重复

Javascript随机数组,不重复
EN

Stack Overflow用户
提问于 2016-01-27 11:32:12
回答 6查看 4.8K关注 0票数 0

所以我试着随机化这些问题,但我总是失败。我试图使用这段代码来添加,但它有一些问题。我把currentQuestion改成了randomQuiz,它起作用了,但还是有一些问题需要解决。

代码语言:javascript
复制
var randomQuiz = Math.floor(Math.random()*quiz.length);

.js文件

代码语言:javascript
复制
    var quiz = [{
      "question": "What is the full form of IP?",
      "choices": ["Internet Provider", "Internet Port", "Internet Protocol"],
      "correct": "Internet Protocol"
    }, {
      "question": "Who is the founder of Microsoft?",
      "choices": ["Bill Gates", "Steve Jobs", "Steve Wozniak"],
      "correct": "Bill Gates"
    }, {
      "question": "1 byte = ?",
      "choices": ["8 bits", "64 bits", "1024 bits"],
      "correct": "8 bits"
    }, {
      "question": "The C programming language was developed by?",
      "choices": ["Brendan Eich", "Dennis Ritchie", "Guido van Rossum"],
      "correct": "Dennis Ritchie"
    }, {
      "question": "What does CC mean in emails?",
      "choices": ["Carbon Copy", "Creative Commons", "other"],
      "correct": "Carbon Copy"
    } , {
      "question": "wsxwsxwsxwsxwsxwsx?",
      "choices": ["wsx", "edc", "qaz"],
      "correct": "wsx"
    } , {
      "question": "qazqazqazqazqazqaz?",
      "choices": ["qaz", "wsx", "edc"],
      "correct": "qaz"
    } , {
      "question": "asdasdasdasdasdasd?",
      "choices": ["asd", "qwe", "zxc"],
      "correct": "asd"
    } , {
      "question": "zxczxczxczxczxczxc?",
      "choices": ["zxc", "asd", "qwe"],
      "correct": "zxc"
    } , {
      "question": "qweqweqweqweqweqwe?",
      "choices": ["qwe", "asd", "zxc"],
      "correct": "qwe"
    }];


    // define elements
    var content = $("content"),
      questionContainer = $("question"),
      choicesContainer = $("choices"),
      scoreContainer = $("score"),
      submitBtn = $("submit");

    // init vars
    var currentQuestion = 0,
      score = 0,
      askingQuestion = true;

    function $(id) { // shortcut for document.getElementById
      return document.getElementById(id);
    }

    function askQuestion() {
      var choices = quiz[currentQuestion].choices,
        choicesHtml = "";

      // loop through choices, and create radio buttons
      for (var i = 0; i < choices.length; i++) {
        choicesHtml += "<input type='radio' name='quiz" + currentQuestion +
          "' id='choice" + (i + 1) +
          "' value='" + choices[i] + "'>" +
          " <label for='choice" + (i + 1) + "'>" + choices[i] + "</label><br>";
      }

      // load the question
      questionContainer.textContent = "Q" + (currentQuestion + 1) + ". " +
        quiz[currentQuestion].question;

      // load the choices
      choicesContainer.innerHTML = choicesHtml;

      // setup for the first time
      if (currentQuestion === 0) {
        scoreContainer.textContent = "Score: 0 right answers out of " +
          quiz.length + " possible.";
        submitBtn.textContent = "Submit Answer";
      }
    }

    function checkAnswer() {
      // are we asking a question, or proceeding to next question?
      if (askingQuestion) {
        submitBtn.textContent = "Next Question";
        askingQuestion = false;

        // determine which radio button they clicked
        var userpick,
          correctIndex,
          radios = document.getElementsByName("quiz" + currentQuestion);
        for (var i = 0; i < radios.length; i++) {
          if (radios[i].checked) { // if this radio button is checked
            userpick = radios[i].value;
          }

          // get index of correct answer
          if (radios[i].value == quiz[currentQuestion].correct) {
            correctIndex = i;
          }
        }

        // setup if they got it right, or wrong
        var labelStyle = document.getElementsByTagName("label")[correctIndex].style;
        labelStyle.fontWeight = "bold";
        if (userpick == quiz[currentQuestion].correct) {
          score++;
          labelStyle.color = "green";
        } else {
          labelStyle.color = "red";
        }

        scoreContainer.textContent = "Score: " + score + " right answers out of " +
          quiz.length + " possible.";
      } else { // move to next question
        // setting up so user can ask a question
        askingQuestion = true;
        // change button text back to "Submit Answer"
        submitBtn.textContent = "Submit Answer";
        // if we're not on last question, increase question number
        if (currentQuestion < quiz.length - 1) {
          currentQuestion++;
          askQuestion();
        } else {
          showFinalResults();
        }
      }
    }

    function showFinalResults() {
      content.innerHTML = "<h2>You've complited the quiz!</h2>" +
        "<h2>Below are your results:</h2>" +
        "<h2>" + score + " out of " + quiz.length + " questions, " +
        Math.round(score / quiz.length * 100) + "%<h2>";
    }

    window.addEventListener("load", askQuestion, false);
    submitBtn.addEventListener("click", checkAnswer, false);

.html文件

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">

<meta name="robots" content="noindex">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Quiz app</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="quiz.css">


</head>
  <body>
    <div id="container">
      <h1>Quiz app</h1>
      <p>There will be no points awarded for unanswered questions.</p>
      <div id="content">
        <h3 id="question"></h3>
        <div id="choices"></div>
        <p><button id="submit"></button></p>
        <p id="score"></p>
      </div>
    </div>
    <script src="quiz.js"></script>


</body>
</html>
EN

回答 6

Stack Overflow用户

发布于 2016-01-27 11:58:38

只需将问题数组打乱,一个接一个地挑选。在简化版本中:

代码语言:javascript
复制
var questions = [1,2,3,4,5,6,7,8,9,10];

function shuffle(a) {
  var cidx, ridx,tmp;
  cidx = a.length;
  while (cidx != 0) {
    ridx = Math.floor(Math.random() * cidx);
    cidx--;
    tmp = a[cidx];
    a[cidx] = a[ridx];
    a[ridx] = tmp;
  }
  return a;
}

function* get_one(arr){
  var idx = arr.length;
  while(idx != 0)
    yield arr[idx--];
}

questions = shuffle(questions);
console.log(questions);

var nextq = get_one(questions);
var alen = questions.length -1;
while(alen--)
  console.log(nextq.next().value);

你不需要那个花哨的生成器,如果你喜欢的话,你可以在一个简单的循环中一个接一个地得到。

票数 2
EN

Stack Overflow用户

发布于 2016-01-27 11:56:50

根据您在测验结束时所做的工作,最简单的方法可能是在问题得到回答后将其从数组中删除。

票数 1
EN

Stack Overflow用户

发布于 2018-06-11 22:54:05

我有另一个非常小的解决方案:

它复制可能值的数组,并删除添加到新数组中的值。

代码语言:javascript
复制
function pickFrom(n, list) {
  const copy = Array.from(list);
  return Array.from(Array(n), () => copy.splice(Math.floor(copy.length * Math.random()), 1)[0]);
}

var quiz = [{
  "question": "What is the full form of IP?",
  "choices": ["Internet Provider", "Internet Port", "Internet Protocol"],
  "correct": "Internet Protocol"
}, {
  "question": "Who is the founder of Microsoft?",
  "choices": ["Bill Gates", "Steve Jobs", "Steve Wozniak"],
  "correct": "Bill Gates"
}, {
  "question": "1 byte = ?",
  "choices": ["8 bits", "64 bits", "1024 bits"],
  "correct": "8 bits"
}, {
  "question": "The C programming language was developed by?",
  "choices": ["Brendan Eich", "Dennis Ritchie", "Guido van Rossum"],
  "correct": "Dennis Ritchie"
}, {
  "question": "What does CC mean in emails?",
  "choices": ["Carbon Copy", "Creative Commons", "other"],
  "correct": "Carbon Copy"
}, {
  "question": "wsxwsxwsxwsxwsxwsx?",
  "choices": ["wsx", "edc", "qaz"],
  "correct": "wsx"
}, {
  "question": "qazqazqazqazqazqaz?",
  "choices": ["qaz", "wsx", "edc"],
  "correct": "qaz"
}, {
  "question": "asdasdasdasdasdasd?",
  "choices": ["asd", "qwe", "zxc"],
  "correct": "asd"
}, {
  "question": "zxczxczxczxczxczxc?",
  "choices": ["zxc", "asd", "qwe"],
  "correct": "zxc"
}, {
  "question": "qweqweqweqweqweqwe?",
  "choices": ["qwe", "asd", "zxc"],
  "correct": "qwe"
}];

console.log(pickFrom(3, quiz));

简化后的示例:

代码语言:javascript
复制
function pickFrom(n, list) {
  const copy = Array.from(list);
  return Array.from(Array(n), () => copy.splice(Math.floor(copy.length * Math.random()), 1)[0]);
}

list = [1, 2, 3];

console.log("Pick 1:", pickFrom(1, list).toString());
console.log("Pick 2:", pickFrom(2, list).toString());
console.log("Pick 3:", pickFrom(3, list).toString());
console.log("Pick 3:", pickFrom(3, list).toString());
console.log("Pick 3:", pickFrom(3, list).toString());

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35028369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档