如何通过循环生成与数值数组等长的循环复用颜色数组
实现方案
你现有代码的问题是:遍历数值数组每一项时,都把完整的8个基础颜色全部插入结果数组,最终得到的数组长度为「数值数组长度 × 基础颜色数量」,不符合需求。
你可以通过索引取余的方式实现循环取色,修复后的代码如下:
const barColors = () => { // 定义基础颜色池 const baseColors = [ 'rgba(3, 4, 94, 1)', 'rgba(3, 4, 94, .8)', 'rgba(3, 4, 94, .6)', 'rgba(3, 4, 94, .4)', 'rgba(3, 4, 94, .2)', 'rgba(3, 4, 94, .4)', 'rgba(3, 4, 94, .6)', 'rgba(3, 4, 94, .8)' ]; const values = [1, 5, 12, 23, 33, 76, 100, 354, 123]; const colorsArr = []; values.forEach((_, index) => { // 用当前索引对基础颜色池长度取余,自动循环匹配颜色 const targetColorIndex = index % baseColors.length; colorsArr.push(baseColors[targetColorIndex]); }); console.log(colorsArr); return colorsArr; };
逻辑说明
以你的示例场景为例:数值数组长度为9,基础颜色池长度为8,索引从0到8遍历:
- 索引0~7时,直接取颜色池对应下标的颜色
- 索引8时,
8 % 8 = 0,取颜色池下标为0的颜色
最终得到的colorsArr长度刚好为9,完全符合需求。就算数值数组有100个元素,该逻辑也能自动循环取色,凑够对应长度的颜色数组。
你也可以用map方法写更精简的版本:
const barColors = () => { const baseColors = [ 'rgba(3, 4, 94, 1)', 'rgba(3, 4, 94, .8)', 'rgba(3, 4, 94, .6)', 'rgba(3, 4, 94, .4)', 'rgba(3, 4, 94, .2)', 'rgba(3, 4, 94, .4)', 'rgba(3, 4, 94, .6)', 'rgba(3, 4, 94, .8)' ]; const values = [1, 5, 12, 23, 33, 76, 100, 354, 123]; return values.map((_, index) => baseColors[index % baseColors.length]); };
内容的提问来源于stack exchange,提问作者Ghatzi
相关产品推荐
相关产品推荐

