基于输入值匹配steps区间返回对应colors数组元素的实现需求
实现returnColor颜色匹配函数
给定两个等长数组:
const colors = ["#00876c", "#50a26f", "#88bb72", "#c1d379", "#fde987", "#fac067", "#f49654", "#e86b4e", "#d43d51"]; const steps = [13.5, 13.6875, 13.875, 14.0625, 14.25, 14.4375, 14.625, 14.8125, 15];
对应规则与函数要求
- 同索引的
steps元素与colors元素一一对应 returnColor函数规则:- 输入值小于
steps最小值时,返回第一个颜色 - 输入值大于
steps最大值时,返回最后一个颜色 - 输入值处于相邻
steps元素之间时,返回前一个steps对应的颜色(示例:returnColor(13.2)返回#00876c,returnColor(13.7)返回#50a26f)
- 输入值小于
实现方案
方法一:遍历匹配
function returnColor(input) { const minStep = steps[0]; const maxStep = steps[steps.length - 1]; if (input < minStep) { return colors[0]; } if (input > maxStep) { return colors[colors.length - 1]; } for (let i = 1; i < steps.length; i++) { if (input < steps[i]) { return colors[i - 1]; } } return colors[colors.length - 1]; }
方法二:用findIndex简化逻辑
function returnColor(input) { const minStep = steps[0]; const maxStep = steps.at(-1); if (input < minStep) return colors[0]; if (input > maxStep) return colors.at(-1); const targetIndex = steps.findIndex(step => step > input); return targetIndex !== -1 ? colors[targetIndex - 1] : colors.at(-1); }
逻辑说明
- 先处理边界情况:输入值超出
steps范围时直接返回首尾颜色 - 区间内的值,找到第一个大于输入值的
steps元素,其前一个索引对应的颜色就是结果 - 若输入值等于
steps最大值,findIndex会返回-1,此时返回最后一个颜色
内容的提问来源于stack exchange,提问作者Vlad Solomon
相关产品推荐
相关产品推荐

