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

如何在无需数组的情况下实现两张卡片同随机颜色绘制?

实现两张卡片同色的修改方案

核心思路

不用数组的话,只需要在遍历卡片时每生成一次随机颜色,就同时应用到相邻的两张卡片即可,不需要提前存储所有颜色。

修改后的代码

for (var i = 0; i < 50; ++i) {
    grid.innerHTML += '<div onclick="go(this)" class="card"></div> '
}

const cards = document.querySelectorAll(".card");

// 假设你已经有这个生成随机颜色的函数,若没有可直接用这段
function generateRandomColor() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgb(${r}, ${g}, ${b})`;
}

const paintCards = () => {
    for (var i = 0; i < cards.length; i += 2) {
        // 仅生成一次随机颜色
        const randomColor = generateRandomColor();
        // 给当前卡片设置颜色
        cards[i].style.backgroundColor = randomColor;
        // 给下一张卡片设置相同颜色
        if (i + 1 < cards.length) { // 兼容卡片总数为奇数的情况,避免越界
            cards[i + 1].style.backgroundColor = randomColor;
        }
    }
};
paintCards();

关键修改点

  • 移除数组依赖:不再提前生成颜色数组,循环内实时生成单种颜色并复用给两张卡片
  • 修复元素访问错误:原代码中cards.style.backgroundColor不合法,cards是NodeList集合,必须通过索引访问单个元素(如cards[i])
  • 边界防护:增加i + 1 < cards.length判断,避免卡片总数为奇数时访问不存在的元素

内容的提问来源于stack exchange,提问作者ארי פיין

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:14:58