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

如何将数组打乱函数应用于彩色方块实现随机排列?

实现彩色方块的随机打乱效果

你可以复用现有的Fisher-Yates洗牌算法来打乱彩色方块,核心思路是把方块对应的颜色信息转化为数组,用相同的逻辑打乱后重新渲染。具体实现如下:

完整代码示例

HTML部分

<!DOCTYPE html>
<html>
<body onload="myFunction()">
  <div id="numbers"></div>
  <br>
  <div id="colors"></div>
</body>
</html>

JavaScript部分

const points = [1, 2, 3, 4, 5, 6];
// 存储初始方块颜色的数组
const colorList = ['red', 'yellow', 'blue', 'orange', 'green', 'purple'];

document.getElementById("numbers").innerHTML = points;

// 抽离通用洗牌函数,复用原有的Fisher-Yates逻辑
function shuffleArray(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    // 解构赋值简化元素交换
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

function myFunction() {
  // 打乱数字数组并更新显示
  shuffleArray(points);
  document.getElementById("numbers").innerHTML = points;
  
  // 打乱颜色数组(复制原数组避免污染初始数据)
  const shuffledColors = shuffleArray([...colorList]);
  const colorsContainer = document.getElementById("colors");
  
  // 清空原有方块
  colorsContainer.innerHTML = '';
  
  // 根据打乱后的颜色重新生成方块
  shuffledColors.forEach(color => {
    const square = document.createElement('div');
    square.style.cssText = 'width:50px; height:50px; display:inline-block;';
    square.style.backgroundColor = color;
    colorsContainer.appendChild(square);
  });
}

关键说明

  • 将原洗牌逻辑抽成通用函数shuffleArray,同时支持数字数组和颜色数组的打乱
  • 通过[...colorList]复制初始颜色数组,确保每次洗牌都基于原始颜色池,避免累积修改
  • 动态生成方块元素并替换容器内容,实现方块排列的随机更新

内容的提问来源于stack exchange,提问作者D Benway

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 10:55:32