javascript - 使用循环随机获取新颜色
问题描述
我试图通过生成随机数来随机化颜色,然后将其应用于数组以获取包含字体颜色和背景颜色的颜色数组。
在每一项“技能”中,我都希望拥有独特的配色方案。所以每次我循环技能数组时,我都会循环颜色数组以获取配色方案。如果此配色方案编号(与 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]})
);
});
解决方案
我认为您的循环方法有很多交互,我的意思是您的循环运行得如此之多以至于它只会结束,直到您找到不在数组中的随机数(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]})
);
});
推荐阅读
- c# - Tuesechkin 响应时间长,返回 null
- node.js - SSD 与 HDD 作为 npm 配置中的性能因素:在哪里放置 .npm 缓存和 node_modules 目录以获得最佳性能?
- c# - CefSharp.Winform - 发送到 Web 表单输入控件时重复输入键盘键
- android-sdk-tools - Android SDK Manager Package Installation getting java.net.SocketException: Connection reset
- php - 如何在 Mysql 中存储 NULL 日期
- cakephp-3.0 - 页面上有多个表单时CakePHP CSRF令牌不匹配
- javascript - 如何从 Safari 钥匙串自动填充调用 ajax respond() 方法到服务器?
- swift - SceneKit 的实例属性“autoenablesDefaultLighting”不起作用
- php - 如何在laravel中加载嵌套关系
- delphi - TWebBrowser 在浏览本地文件后将 HTML 代码插入正文