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

如何将随机颜色数组应用到JavaScript记忆游戏的新卡片上?

解决记忆游戏中卡片颜色匹配的问题

你的问题出在这几个地方:

  • 每次调用generateArrayOfColors()都会生成一组全新的25个随机颜色,没法让两张卡片共用同一个颜色
  • 没有把生成的25种颜色各复制一份,凑出50个元素的数组来对应50张卡片
  • 循环里反复执行document.querySelectorAll(".card")完全没必要,会重复查询DOM,拖慢性能

正确的实现步骤:

  1. 先生成包含25种随机颜色的数组
  2. 将这个数组复制一份,合并成一个50个元素的数组(每种颜色出现两次)
  3. 把这个50元素的数组随机打乱(保证卡片颜色随机分布)
  4. 一次性获取所有卡片元素,然后循环给每个卡片设置对应的颜色

修改后的完整代码:

document.addEventListener('DOMContentLoaded', () => {
    function generateRandomColor() {
        const hexValues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
        let randomNum = "";
        for (let i = 0; i < 6; i++) {
            randomNum += hexValues[Math.floor(Math.random() * 16)];
        }
        return `#${randomNum}`;
    }

    const grid = document.querySelector(".grid");

    // 先创建50张卡片
    for (let i = 0; i < 50; ++i) {
        grid.innerHTML += '<div class="card"></div>';
    }    

    function generateArrayOfColors() { 
        const colors = [];
        for (let i = 0; i < 25; i++) { 
            colors.push(generateRandomColor());
        }
        // 复制一份颜色,合并成50个元素的数组
        return [...colors, ...colors];
    }

    // 洗牌函数:打乱数组顺序
    function shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    }

    // 生成并打乱颜色数组
    const colorPairs = shuffleArray(generateArrayOfColors());
    // 一次性获取所有卡片
    const cards = document.querySelectorAll(".card");

    // 给每个卡片设置颜色
    for (let i = 0; i < 50; i++) { 
        cards[i].style.backgroundColor = colorPairs[i];
    } 
});

关键修改说明:

  • 使用[...colors, ...colors]把25种颜色复制一份,得到50个元素的数组,每种颜色恰好出现两次
  • 新增shuffleArray函数打乱颜色数组,确保卡片颜色随机分布,符合记忆游戏的需求
  • 把document.querySelectorAll(".card")移到循环外面,只查询一次DOM
  • 用const替代不必要的var,提升代码的严谨性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:32:15