【问题标题】:How to assign specific colors to an object randomly?如何为对象随机分配特定颜色?
【发布时间】:2020-03-08 16:10:28
【问题描述】:

我有 6 个方格,我想为它们分配 6 种已经定义的颜色,但是是随机的。所以 1 个方块应该有 1 种颜色,每次我点击“再次播放”时,它们应该随机混合。到目前为止,我已经设法使所有方块都使用六种颜色中的一种,但是由于它们只是随机选择它们,因此经常发生例如我有 3 种灰色但 0 种红色的情况。 我不知道如何更好地解释这一点,所以如果您有任何问题,我很乐意回答。

HTML:

<div id="container">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
</div>

JS:

var squares = $(".square");
var colors = {
    'yellow': 'rgb(255, 255, 0)',    
    'orange': 'rgb(255, 153, 0)',
    'green': 'rgb(0, 255, 0)',
    'blue': 'rgb(0, 0, 255)',
    'gray': 'rgb(128, 128, 128)',
    'purple': 'rgb(153, 0, 255)'
};

for(var i=0; i < squares.length; i++) {
    squares[i].style.backgroundColor = randomColors();
    squares[i].style.display = "block";
}

function randomColors(ranCol) { 
    var ranCol = Object.keys(colors)[Math.floor(Math.random()*Object.keys(colors).length)];
    return ranCol;
}

【问题讨论】:

  • Shuffle你的颜色数组然后按顺序分配?
  • 你应该对概率进行加权,这样干旱越少的数字被抽水的概率越大
  • 或者用delete去掉选中的颜色

标签: javascript arrays loops object


【解决方案1】:

您可以shuffle an array of the colors,然后从洗牌结果中分配它们:

var array = Object.keys(colors);
shuffleArray(array);
for(var i=0; i < squares.length; i++){
    squares[i].style.backgroundColor = colors[array[i]];
    squares[i].style.display = "block";
}

如果你不想走那条路,你可以把它们放在一个数组中并从中随机选择颜色,每次都去掉你选择的颜色:

var array = Object.keys(colors);
for(var i=0; i < squares.length; i++){
    var index = Math.floor(Math.random() * array.length);
    var color = array[index];
    array.splice(index, 1); // Remove that entry
    squares[i].style.backgroundColor = colors[color];
    squares[i].style.display = "block";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 2020-07-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多