Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/425.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
数组上的Javascript随机,不重复_Javascript - Fatal编程技术网

数组上的Javascript随机,不重复

数组上的Javascript随机,不重复,javascript,Javascript,所以我试着把这些问题随机化,但我一直失败。我尝试使用此代码来添加,但存在一些问题。我将currentQuestion改为RandomQuike,效果不错,但还是有一些问题需要解决 var randomQuiz = Math.floor(Math.random()*quiz.length); .js文件 var quiz = [{ "question": "What is the full form of IP?", "choices": ["Internet P

所以我试着把这些问题随机化,但我一直失败。我尝试使用此代码来添加,但存在一些问题。我将currentQuestion改为RandomQuike,效果不错,但还是有一些问题需要解决

var randomQuiz = Math.floor(Math.random()*quiz.length);
.js文件

    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);
var测验=[{
“问题”:“知识产权的完整形式是什么?”,
“选择”:[“互联网提供商”、“互联网端口”、“互联网协议”],
“正确”:“互联网协议”
}, {
“问题”:“谁是微软的创始人?”,
“选择”:[“比尔·盖茨”、“史蒂夫·乔布斯”、“史蒂夫·沃兹尼亚克”],
“正确”:“比尔·盖茨”
}, {
“问题”:“1字节=?”,
“选项”:[“8位”、“64位”、“1024位”],
“正确”:“8位”
}, {
“问题”:“C编程语言是由谁开发的?”,
“选择”:[“Brendan Eich”、“Dennis Ritchie”、“Guido van Rossum”],
“正确”:“丹尼斯·里奇”
}, {
“问题”:“CC在电子邮件中是什么意思?”,
“选择”:[“复写”、“知识共享”、“其他”],
“正确”:“复印件”
} , {
“问题”:“WSXWSXWSXWSXWSXWSXWSX?”,
“选择”:[“wsx”、“edc”、“qaz”],
“正确”:“wsx”
} , {
“问题”:“qazqazqazqazqazqaz?”,
“选择”:[“qaz”、“wsx”、“edc”],
“正确”:“qaz”
} , {
“问题”:“asdasdasd?”,
“选择”:[“asd”、“qwe”、“zxc”],
“正确”:“asd”
} , {
“问题”:“zxczxczxczxczxczxc?”,
“选择”:[“zxc”、“asd”、“qwe”],
“正确”:“zxc”
} , {
“问题”:“qweqweqweqweqweqwe?”,
“选择”:[“qwe”、“asd”、“zxc”],
“正确”:“qwe”
}];
//定义元素
变量内容=$(“内容”),
questionContainer=$(“问题”),
choicesContainer=$(“选项”),
scoreContainer=$(“分数”),
submitBtn=$(“提交”);
//初始化变量
var currentQuestion=0,
分数=0,
问问题=正确;
函数$(id){//document.getElementById的快捷方式
返回文档.getElementById(id);
}
函数askQuestion(){
var choices=测验[currentQuestion]。选项,
choicesHtml=“”;
//循环选择,并创建单选按钮
for(var i=0;i”;
}
//加载问题
questionContainer.textContent=“Q”+(当前问题+1)+”+
测验[当前问题]。问题;
//加载选项
choicesContainer.innerHTML=choicesHtml;
//第一次安装
如果(currentQuestion==0){
scoreContainer.textContent=“分数:0个正确答案”+
quick.length+“可能。”;
submitBtn.textContent=“提交答案”;
}
}
函数checkAnswer(){
//我们是在问一个问题,还是继续下一个问题?
如果(提问){
submitBtn.textContent=“下一个问题”;
问问题=错误;
//确定他们单击了哪个单选按钮
var userpick,
更正索引,
radios=document.getElementsByName(“测验”+当前问题);
对于(变量i=0;i
.html文件

<!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>

测验应用程序
测验应用程序
未回答的问题将不予计分


您可以使用数组存储已询问的问题 在随机化过程中每次检查数组,然后选择问题

var track=new Array();

while(true)//loop until Unique number
{
    var randomQuiz=Math.floor(Math.random()*quiz.length);

     if(track.indexOf(randomQuiz)==-1)//if you have got your unique random number
     {
        track.push(random);
        break;
     }
}

编辑:正如Stephen p指出的,从数组中删除元素可能会导致性能问题,正如Brent Waggoner所建议的那样,从数组中删除元素更符合逻辑。

您可以使用数组来存储已询问的问题 在随机化过程中每次检查数组,然后选择问题

var track=new Array();

while(true)//loop until Unique number
{
    var randomQuiz=Math.floor(Math.random()*quiz.length);

     if(track.indexOf(randomQuiz)==-1)//if you have got your unique random number
     {
        track.push(random);
        break;
     }
}

编辑:正如Stephen p指出的,从数组中删除元素可能会导致性能问题,这是Brent Waggoner建议的更符合逻辑的做法。

您需要编写一些逻辑。下面是一个示例

    var list = [1, 2, 3, 4, 5];
    var listDone = [];        
    var inProcess = true;
    while(inProcess){
        var randomQuiz = Math.floor(Math.random() * list.length);

        var isDone = false;
        for (var j = 0; j < listDone.length; j++) {
            if (listDone[j] === randomQuiz)
                isDone = true;
        }
        if (!isDone) {
            console.log(list[randomQuiz]);//Display if not Done.
            listDone.push(randomQuiz);
        }

        if (list.length == listDone.length)
            inProcess = false;

    }
var列表=[1,2,3,4,5];
var listDone=[];
var-inProcess=true;
while(进程中){
var randomquick=Math.floor(Math.random()*list.length);
var isDone=fa
var questionCounter = 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"
}];

var currentQuestion = Math.floor(Math.random() * quiz.length);



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


  score = 0,
  askingQuestion = true;

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

function askQuestion() {

 //increment the counter
    questionCounter++;

  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" + (questionCounter) + ". " +
    quiz[currentQuestion].question;

  // load the choices
  choicesContainer.innerHTML = choicesHtml;

  // setup for the first time
  if (questionCounter === 1) {
    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);
var shuffled = quiz.map(x => { return {data: x, srt: Math.random()}})
.sort((a,b) => {return a.srt - b.srt})
.map(x => x.data);