首页 > 解决方案 > 使用循环随机获取新颜色

问题描述

我试图通过生成随机数来随机化颜色,然后将其应用于数组以获取包含字体颜色和背景颜色的颜色数组。

在每一项“技能”中,我都希望拥有独特的配色方案。所以每次我循环技能数组时,我都会循环颜色数组以获取配色方案。如果此配色方案编号(与 randomNumber 相同)已在使用中,我将再次随机。我用 do/while 循环来做到这一点。当找不到颜色时,它会将其推送到 usedColors 数组并绘制图片。

出于某种原因,我仍然得到相同的颜色。我在底部贴了两张图片。Console.log 图像是关于 usedColors 数组(随机生成的数字)

var usedColors = [];
    $.each(knowledges, (i, knowledge) => {                                  
       do {
          var r = Math.floor(Math.random() * Math.floor(colors.length)),
              rColors = colors[r];                

          } while ($.inArray(r, usedColors) == 0);
          usedColors.push(r);

          $("#knowledges div").append(            
              $("<p />").addClass("knowledge").text(knowledge).css({"background-color": rColors[0], "color": rColors[1]})
          );
    });

在此处输入图像描述

在此处输入图像描述

标签: javascriptdo-while

解决方案


我认为您的循环方法有很多交互,我的意思是您的循环运行得如此之多以至于它只会结束,直到您找到不在数组中的随机数(A short performance problem)。一种使数组元素随机的替代方法:

function shuffleArray(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

const colors = [["black","green"], ["white","blue"], ["pink","white"]];
let usedColors = shuffleArray(colors);

//You can now do this:

$.each(knowledges, (i, knowledge) => {
    $("#knowledges div").append(            
        $("<p />").addClass("knowledge").text(knowledge).css({"background-color": usedColors[i][0], "color": usedColors[i][1]})
    );
});


推荐阅读