如何确保随机生成器不会连续两次使用相同的数字?

问题描述 投票:0回答:0

目前,我正在尝试创建 4 个 div(正方形),当您单击其中一个时,它会选择一种随机颜色。这是通过获取一个随机数并将随机数与数组的索引值相关联来完成的。然而,代码使得如果颜色是蓝色,它将再次变成蓝色,这似乎违反直觉。我想让它不会连续两次重复使用相同的索引值,即 I.E 颜色。我正在考虑在获取值时从数组中删除索引值,并在第二次运行后重新输入它。但是我该怎么做呢?还有其他方法吗?

我尝试拼接数组索引并重新添加它,但这只是让我的代码中断,这很可能是因为我不知道如何正确实现它。

HTML:

<div id="box_Container">
     <div class="thirdBoxes" onclick="changeColorThird()"></div>
     <div class="thirdBoxes" onclick="changeColorThird()"></div>
     <div class="thirdBoxes" onclick="changeColorThird()"></div>
     <div class="thirdBoxes" onclick="changeColorThird()"></div> 
</div>

JavaScript:


    const colors = ["red", "blue", "green", "yellow", "aqua", "orange", "black", "purple"];
    let prevColor = "";
    let newColor = "";
    
    function changeColorThird(){
        var randomColor = Math.floor(Math.random()*colors.length);
        if(this.style.background = colors[randomColor]) {
            this.style.background = colors[randomColor];
        } else {
            this.style.background = colors[randomColor];
        }
        console.log(randomColor);
    }
    
    let thirdBox = document.getElementsByClassName("thirdBoxes");
    
    for(let i = 0; i < thirdBox.length; i++) {
        thirdBox[i].addEventListener("click", changeColorThird)
    }

javascript arrays math dom random
© www.soinside.com 2019 - 2024. All rights reserved.