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

如何在JavaScript中将颜色数组元素均匀映射到数值数组元素?

数组元素均匀分配颜色的实现方案

要实现将plots数组的元素均匀分配到colors数组的颜色中,核心是先计算每个颜色应分配的元素数量,再根据元素索引匹配对应的颜色。以下是具体实现:

代码实现

const colors = ['green', 'yellow', 'red']
const plots = [0, 10, 40, 90, 150, 230, 250]

const totalPlots = plots.length;
const colorCount = colors.length;
const baseNum = Math.floor(totalPlots / colorCount); // 每个颜色基础分配数
const extraNum = totalPlots % colorCount; // 需要多分配1个的颜色数量

const withColors = plots.map((val, idx) => {
  // 计算当前元素对应的颜色索引
  const threshold = (baseNum + 1) * extraNum;
  const colorIdx = idx < threshold 
    ? Math.floor(idx / (baseNum + 1)) 
    : extraNum + Math.floor((idx - threshold) / baseNum);
  
  return { value: val, color: colors[colorIdx] };
});

console.log(withColors);

逻辑说明

  1. 计算分配基数:用plots的长度除以colors的长度,得到每个颜色的基础分配数baseNum,余数extraNum表示有多少个颜色需要多分配1个元素。
  2. 划分索引区间:前extraNum个颜色每个分配baseNum+1个元素,剩下的颜色分配baseNum个元素。
  3. 匹配颜色:根据当前元素的索引idx判断属于哪个区间,从而得到对应的颜色索引,最终返回带颜色的对象。

运行代码后,输出结果完全符合预期:

[
  {value: 0, color: 'green'},
  {value: 10, color: 'green'},
  {value: 40, color: 'yellow'},
  {value: 90, color: 'yellow'},
  {value: 150, color: 'red'},
  {value: 230, color: 'red'},
  {value: 250, color: 'red'},
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:50:39