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

如何循环复用固定长度颜色数组为动态分类数组绑定背景色属性

实现方案

核心逻辑是利用取模运算符%实现颜色数组的循环取值:用category数组当前遍历项的索引,对bgColor数组的长度取余,得到的余数就是当前项对应的bgColor索引,超出bgColor长度的项会自动从第一个颜色重新开始赋值。

方案1:生成新数组(推荐,无副作用)

该方案不会修改原始的category数组和数组内的对象,适合需要保留原数据的场景:

const coloredCategory = category.map((item, index) => {
  const colorIndex = index % bgColor.length;
  // 展开原对象新增color属性,不修改原对象
  return {
    ...item,
    color: bgColor[colorIndex]
  };
});

方案2:直接修改原数组

如果不需要保留原始category数组,可以直接遍历修改:

category.forEach((item, index) => {
  const colorIndex = index % bgColor.length;
  item.color = bgColor[colorIndex];
});

可选边界处理

如果存在bgColor为空数组的可能,可以增加兜底逻辑避免取到无效值:

// 兜底默认颜色为灰色
const color = bgColor[index % bgColor.length] ?? '#cccccc';

内容的提问来源于stack exchange,提问作者Juhi Kukreja

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:24:03