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

基于输入值匹配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);
}

逻辑说明

  1. 先处理边界情况:输入值超出steps范围时直接返回首尾颜色
  2. 区间内的值,找到第一个大于输入值的steps元素,其前一个索引对应的颜色就是结果
  3. 若输入值等于steps最大值,findIndex会返回-1,此时返回最后一个颜色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:45:28