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

如何生成categoryData无重复随机项并为CategoryCard循环绑定colors?

解决方案

1. 获取10个不重复的随机分类项

要避免重复选取,推荐使用Fisher-Yates洗牌算法先打乱原数组,再截取前10项,这种方法效率高且能保证完全不重复:

// 复制原数组,避免修改原始数据
const shuffledCategories = [...categoryData];
// Fisher-Yates洗牌逻辑
for (let i = shuffledCategories.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [shuffledCategories[i], shuffledCategories[j]] = [shuffledCategories[j], shuffledCategories[i]];
}
// 取前10个不重复随机项
const randomCategories = shuffledCategories.slice(0, 10);

如果categoryData的长度不足10,建议先判断长度(比如categoryData.length >=10),避免截取时出现空项。

2. 循环绑定颜色到CategoryCard

在map函数中利用数组索引,通过取模运算实现colors数组的循环复用:

<div className="grid grid-rows-1 grid-flow-col w-[2360px] h-[233px] max-h-[233px] gap-x-3">
  {randomCategories.map((item, index) => {
    // 用索引对colors长度取模,实现循环取色
    const color = colors[index % colors.length];
    return (
      <CategoryCard
        key={item?.id}
        name={item?.name}
        image={item?.image}
        gradientStart={color["gradient-start"]}
        gradientEnd={color["gredient-end"]}
      />
    );
  })}
</div>

注意:你的colors数组里存在拼写错误——gredient-end应为gradient-end,建议修正后再使用,避免取值失败。

完整代码示例

// 处理不重复随机项
const shuffledCategories = [...categoryData];
for (let i = shuffledCategories.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [shuffledCategories[i], shuffledCategories[j]] = [shuffledCategories[j], shuffledCategories[i]];
}
const randomCategories = shuffledCategories.slice(0, 10);

// 渲染组件
return (
  <div className="grid grid-rows-1 grid-flow-col w-[2360px] h-[233px] max-h-[233px] gap-x-3">
    {randomCategories.map((item, index) => {
      const color = colors[index % colors.length];
      return (
        <CategoryCard
          key={item?.id}
          name={item?.name}
          image={item?.image}
          gradientStart={color["gradient-start"]}
          gradientEnd={color["gredient-end"]}
        />
      );
    })}
  </div>
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:38:11