[英]JS get random value from array and update array
我需要你的幫助! 我正在生成一個與問題編號相對應的數組。
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
然后我用這個數字附加相應的問題,回答然后點擊。 然后我從這樣的數組中得到一個新值
const randomQ = arrayCharge;
const random = Math.floor(Math.random() * randomQ.length);
它可以工作,並且會收取一個新問題,但數組仍然相同。 我試過這個
var remQ = arrayCharge.indexOf(randomQ[random]);
arrayCharge.splice(remQ,1);
但它不起作用;-(
非常感謝你的幫助。 尼古拉斯
這是幫助理解的完整代碼! 抱歉,我應該從一開始就這樣做。
<!DOCTYPE HTML>
<!--
Hyperspace by HTML5 UP
html5up.net | @ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Repérez vos messages contraignants - Quiz</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript>
<link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Sidebar -->
<!-- <section id="sidebar">
</section> -->
<!-- Wrapper -->
<div id="wrapper">
<!-- Intro -->
<section id="intro" class="wrapper style1 fullscreen fade-up">
<div class="inner">
<header>
<button id="start">Commencer</button>
<p> </p>
</header>
<form action="" method="post">
<p id="Qnum"></p>
<p id="Q" data-qnumber="" data-type=""></p>
<section id="answer">
<input type="submit" id="1" name="R1" value="Non">
<input type="submit" id="2" name="R2" value="Parfois">
<input type="submit" id="3" name="R3" value="Souvent">
<input type="submit" id="4" name="R4" value="Oui">
</section>
</form>
</div>
</section>
<!-- Footer -->
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script>
$(document).ready(function() {
if (localStorage.getItem("clic") >= 45) {
console.log('45');
sessionStorage.clear();
localStorage.clear();
}
var Q1 = [1, "My first question", "FP"];
var Q2 = [2, "My second question", "SP"];
var Q3 = [3, "My third question", "SE"];
var Q4 = [4, "My foutrh question", "DP"];
var Q5 = [5, "My fifth question", "FP"];
//etc... until Q45
if (sessionStorage.getItem("FP") == null) {
$("form").attr("action", "driversV2.php");
$("#answer").hide();
$("#start").click(function() {
$("#Qnum").append(1+" / 45");
$("#Q").append(Q1[1]).attr("data-qnumber", Q1[0]).attr("data-type", Q1[2]);
$("#answer").show();
$("header").hide();
var pageType = $("#Q").attr("data-type");
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
localStorage.setItem("clic", 1);
});
});
} else {
$("header").hide();
var clicNum = parseInt(localStorage.getItem("clic"));
var QNumber = clicNum + 1;
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
const randomQ = arrayChargeNew;
const random = Math.floor(Math.random() * randomQ.length);
console.log('valeur random new = '+randomQ[random]);
var QCharge = "Q" + randomQ[random];
var Charge = eval(QCharge);
localStorage.setItem("random",randomQ[random]);
$("#Qnum").append(QNumber+" / 45");
$("#Q").append(Charge[1]).attr("data-qnumber", Charge[0]).attr("data-type", Charge[2]);
//création de la variable du type de question
var pageType = $("#Q").attr("data-type");
//alert(sessionStorage.getItem(pageType));
if (localStorage.getItem("clic") < 44) {
$("form").attr("action", "driversV2.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
} else {
$("form").attr("action", "driversResultat.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
}
}
});
</script>
</body>
</html>
尼古拉斯,這就是我認為你應該做的:
// Create the array in whatever way you need to var arrayCharge = []; for (var i = 2; i <= 45; i++) { arrayCharge.push({"questionnumber": i, "question": "Text of question " + i}); } // Just confirm the length of the array - should be 44 console.log(arrayCharge.length); // Generate a random number based on the length of the array var rnd = Math.floor(Math.random() * arrayCharge.length); // Get the question at the randomly generated index number let thisQuestion = arrayCharge[rnd]; // Check that we have a random question console.log(thisQuestion.questionnumber); console.log(thisQuestion.question) // Present the question to the user on the page // The user completes question and clicks "Submit" // Now remove the question, using the SAME index number arrayCharge.splice(rnd,1); // Check that the array has lost an entry - the size should now be 43 console.log(arrayCharge.length);
尼古拉斯,這就是你最終應該做的事情:
// From my library js file // returns a random number in the given range function getRandomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // Variables for objects that need to be available throughout let availableQuestions = []; let rnd = 0; let counter = 0; // Populate the question array - how this is done depends on where the question data comes from function createQuestions() { availableQuestions.length = 0; for (let i = 1; i <= 10; i++) { availableQuestions.push({"questionnumber": i, "question": "Text for question " + i}); } } // Pick a random question and display that to the user function getRandomQuestion() { let osQuestions = availableQuestions.length; let qnElement = document.getElementById("questionnumber"); let qElement = document.getElementById("question"); let sButton = document.getElementById("submit"); let rButton = document.getElementById("restart"); // If there are no more questions, stop if (osQuestions == 0) { qnElement.innerHTML = "Finished!"; qElement.innerHTML = ""; sButton.style.display = "none"; rButton.style.display = "inline"; } else { // display a sequential question number rather than the actual question number counter++; rnd = getRandomNumber(0, osQuestions - 1); let thisQuestion = availableQuestions[rnd]; qnElement.innerHTML = "Question: " + counter + " (Actually question: " + thisQuestion.questionnumber + ")"; qElement.innerHTML = thisQuestion.question; } } // Process the user's answer and remove the question from the array function submitAnswer() { // ALSO Add in what needs to be done to update backend database etc when the user clicks submit availableQuestions.splice(rnd, 1); getRandomQuestion(); } // Reset everything - for testing purposes only function restart() { let qnElement = document.getElementById("questionnumber"); let qElement = document.getElementById("question"); let sButton = document.getElementById("submit"); let rButton = document.getElementById("restart"); qnElement.innerHTML = ""; qElement.innerHTML = ""; sButton.style.display = "inline"; rButton.style.display = "none"; // Reset the displayed question number counter counter = 0; createQuestions(); getRandomQuestion(); } // Needed to populate the array and display the first question function runsetup() { createQuestions(); getRandomQuestion(); } window.onload = runsetup;
<div id="questionnumber"></div> <hr> <div id="question"></div> <button id="submit" onclick="submitAnswer();">Submit</button> <button id="restart" onclick="restart();" style="display:none;">Restart</button>
我已經包含了一個計數器變量,以便用戶看不到實際的問題編號 - 只有 1、2、3 等,但我已經顯示了實際的問題編號,以便您可以看到它的工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.