【问题标题】:How do I get multiple random different items from an array in javascript?如何从javascript中的数组中获取多个随机不同的项目?
【发布时间】:2019-11-26 18:28:24
【问题描述】:
function question1(){
    if(sessionStorage.quizCounter == 0){
        var qa0 = qs[Math.floor(Math.random() * 19)];
        document.getElementById('questions_container').innerHTML = qa0[0]

        for (let i = 1; i <= 3; i++) {
            document.getElementById('answers_container').innerHTML += qa0[Math.floor((Math.random() * 2))+1];
        }
    }
}

这是我的功能,它应该将数组中的第一项放在 &lt;div id="questions_container"&gt; 中,这可以工作,但第二部分 - for 循环 - 不起作用。

for 循环应该将最后 3 个项目随机粘贴到 &lt;div id="answers_container"&gt; 中。而且我不知道如何做到这一点。就目前而言,它会打印重复项,这是我不想要的。

qa0[0] 始终是问题所在。 qa0[1, 2, 3] 总是答案。 qa0[] 始终包含 4 个项目。我需要第一项始终在 qa0[0] 上。

【问题讨论】:

    标签: javascript arrays sorting random


    【解决方案1】:

    我想以最简单的方式回答这个问题。

    如果您不需要担心位置,您可以将数据随机化,然后删除最后的 N 项。

    function shuffle(array) {
      array.sort(() => Math.random() - 0.5);
    }
    

    这会打乱你的数组,本质上是随机化的。然后,您可以从末尾弹出项目

    function randomitems(arr, returnedCount){
        function shuffle(array) {
          array.sort(() => Math.random() - 0.5);
        }
        const clonedData = arr.slice()
        shuffle(clonedData)
        if ( returnedCount === undefined) return clonedData;
        return clonedData.slice(-1 * returnedCount)
    }
    

    这会占用一些空间,因为我不想更改原始对象。

    流畅,快速。没有超级复杂的代码。

    它将返回一个随机列表,如果基础 arr 中有重复项,它将仅返回重复项。否则,它将保持数组项的唯一性。

    这将返回一个项目数组,然后您可以循环该列表或执行您特别需要的任何操作以获得所需的结果。

    如果你想获得超级计算机科学,我还可以提供一个超优化的随机集,但在你的数据集开始变大之前,这可能不会带来太多回报。

    这将在以下情况下为您使用:

    // This will link all the questions and possible answers together.
    qa0 = [question, ans1, ans2, ans3, ans4].
    // The next step is that you need to shuffle the answers.
    tmpVar = [].concat(qa0[0], randomizeItems(qa0.slice(1))); // no number will just return the shuffled set.
    qa0 = tmpVar;  // You could likely just not even use this tmpVar and just do assignment if you really wanted to.
    

    这样,qa0 的问题将是 0 索引,并且之后的所有项目都被打乱。所以它看起来像:qa0 = [ question, ans3, ans1, ans2, ans4];

    【讨论】:

    • 我需要第一项始终位于数组 [0] 上。对不起,应该在问题中澄清。你还有什么建议
    • 该死的救世主。谢谢
    猜你喜欢
    • 2017-02-01
    • 1970-01-01
    • 2021-06-30
    • 2017-12-29
    • 2011-08-20
    • 2020-05-13
    相关资源
    最近更新 更多