【问题标题】:JS get random value from array and update arrayJS从数组中获取随机值并更新数组
【发布时间】:2020-10-01 14:59:21
【问题描述】:

我需要你的帮助! 我正在生成一个对应于问题编号的数组。

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>&nbsp;</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>

【问题讨论】:

  • 什么不完全有效?我们可能需要更多上下文,例如arrayCharge 是如何使用的?
  • 事实上,我使用“randomQ[random]”,并且在提出问题时我想从数组中删除 iot。每个问题都像这样:var Q45 = [45, "Je pense qu'on peut s'améliorer en travaillant dur.", "FE"]; var QCharge = "Q" + randomQ[随机]; var Charge = eval(QCharge); $("#Q").append(Charge[1]).attr("data-qnumber", Charge[0]).attr("data-type", Charge[2]);
  • 我认为这是因为您混淆了 random 和 index.html。您的最后一段代码尝试查找与随机数匹配的 value 的索引。但是,随机数是基于数组的长度。因此,随机数可能已经作为 value 从数组中删除,但仍作为索引号存在,或者可能作为 value 存在但不作为索引号
  • 其实我是用值的索引把它从原始数组中去掉
  • 是的,但是 random 数字是基于数组的长度而不是数组中的 values

标签: javascript arrays random


【解决方案1】:

尼古拉斯,你应该得到这样的结果:

// 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 等,但我已经显示了实际的问题编号,以便您可以看到它正在工作

【讨论】:

  • 哇侯!!你太棒了。太感谢了。我已经在这几天了,很高兴看到你做事的方式,对我来说有很多东西要学习。
  • :D np - 下一步是考虑如果用户在回答问题的过程中重新加载页面会发生什么。但是,一旦您有了基本的变量和函数结构,这就会变得更容易考虑。
  • 然后我可以存储他最后回答的问题编号。用上面的代码确定一个问题只会出现一次吗?
  • 您需要存储所有已回答的问题,当他重新加载页面时,检索存储的列表,阅读它找到已回答的问题编号并使用它从显示下一个问题之前的 availableQuestions 数组。
【解决方案2】:

尼古拉斯,我认为你应该这样做:

// 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);

【讨论】:

  • 您好 ATD,再次感谢您提供此解决方案,这样直接创建带有问题的数组要好得多。提交“rnd”时仍然存在问题,但是当我再次提交新问题时,它会删除实际的“rnd”,但之前的问题又回到了列表中,它可以再次选择这个问题。
  • 这完全取决于提交的方式和时间。如果用户实际上提交了一个触发页面刷新的表单,那么问题将再次出现,因为您正在重新加载页面。但是,如果此时未提交页面,则只要在函数之外定义 rnd 变量,它就会一直保留 - 因此,在关闭窗口之前,它是一个可用的全局变量。那么,当他们提交答案时会发生什么?
  • 我会改变这一点,非常感谢,我想我这里有我需要的一切。太好了!!
  • 最后评论,数组的创建需要在函数外还是在函数内?
  • 变量应该在函数之外——这样它们就可以在代码中的任何地方使用。函数应该在那里生成或控制事物。上述工作是因为我们只处理您的整个代码的缩减版本。因此,将所有变量放在代码的顶部。创建函数以生成问题数组、获取随机数、提取随机问题、填充页面并在用户单击提交时从数组中删除问题。然后,当页面加载或用户准备好下一个问题时,您只需调用相应的函数。
猜你喜欢
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 2022-10-08
  • 1970-01-01
  • 2010-12-11
相关资源
最近更新 更多