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

如何用JavaScript基于Array.map索引实现黑白双列交替网格

双列网格颜色匹配逻辑实现

规律推导

整理给定的索引与颜色对应规则,可以发现颜色每4个索引为一个循环周期:

  • 索引对4取余结果为0、3时,格子颜色为白色
  • 索引对4取余结果为1、2时,格子颜色为黑色

代码实现

直接在Array.map的回调里通过index计算对应颜色即可,无需依赖CSS方案:

const gridItems = Array.from([1,2,3,4,5,6,7,8,9,10]).map((num, index) => {
  const remainder = index % 4;
  const bgColor = remainder === 1 || remainder === 2 ? 'black' : 'white';
  // 此处替换为你的列表项渲染逻辑即可
  return {
    content: num,
    bgColor
  }
})

// 规则验证:输出对应索引和颜色
gridItems.forEach((item, idx) => console.log(`${idx}-${item.bgColor}`))

运行上述代码的输出完全匹配预期规则:0-white 1-black 2-black 3-white 4-white 5-black 6-black 7-white 8-white 9-black

内容的提问来源于stack exchange,提问作者Karl Taylor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:39:18