使用Math.random()生成随机背景色时如何避免连续两次颜色重复
解决方案
核心思路是新增变量记录上一次使用的颜色索引,每次生成随机数时排除该索引即可避免连续重复。
你不需要修改HTML代码,仅需调整JS逻辑如下:
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"]; const btn = document.getElementById("btn"); const color = document.querySelector(".color"); // 新增变量存储上一次使用的颜色索引,初始值设为-1(不存在的数组索引) let lastIndex = -1; btn.addEventListener("click", function() { let randomNumber = getRandomNumber() // 如果生成的索引和上次一致,就重新生成直到拿到不同的索引 while(randomNumber === lastIndex) { randomNumber = getRandomNumber() } // 更新上次使用的索引供下次判断 lastIndex = randomNumber document.body.style.backgroundColor = colors[randomNumber]; color.textContent = colors[randomNumber] }) function getRandomNumber() { return Math.floor(Math.random() * colors.length) }
修改说明
- 新增
lastIndex变量记录上一次选中的颜色数组索引,初始值设为-1避免和首次生成的有效索引重合 - 点击事件中增加循环判断逻辑,确保生成的新索引和上一次索引不重复
- 每次完成颜色切换后更新
lastIndex的值,供下一次点击时校验
只要colors数组长度≥2,该逻辑可100%避免连续两次出现相同颜色的问题。
内容的提问来源于stack exchange,提问作者Saeed Ghezel Arsalan
相关产品推荐
相关产品推荐

