You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:18:03