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

如何基于数值范围检索JavaScript对象的对应值?

基于数值范围检索对象对应值的解决方案

实现思路

  1. 将对象的字符串键转换为数值阈值,与对应值组成条目数组。
  2. 按阈值从小到大排序条目数组,确保按顺序匹配范围。
  3. 对输入值,找到第一个大于等于它的阈值并返回对应值;若输入超过所有阈值,则返回最后一个条目对应的数值。

代码实现

const ind_ind = {
    '25000': 200,
    '100000': 375,
    '200000': 750,
    '400000': 900
};

// 预处理:转换为排序后的数值阈值-值条目数组
const sortedEntries = Object.entries(ind_ind)
    .map(([key, value]) => [Number(key), value])
    .sort((a, b) => a[0] - b[0]);

function getCorrespondingValue(input) {
    // 处理输入:支持数字或带千分点的字符串(如"25.000"转为25000)
    let numInput;
    if (typeof input === 'string') {
        numInput = Number(input.replace(/\./g, ''));
    } else {
        numInput = Number(input);
    }

    if (isNaN(numInput)) {
        throw new Error('输入无效:必须是数字或可转换为数字的字符串');
    }

    // 匹配对应阈值范围
    const matchedEntry = sortedEntries.find(([threshold]) => threshold >= numInput);
    return matchedEntry ? matchedEntry[1] : sortedEntries[sortedEntries.length - 1][1];
}

测试示例

// 测试所有示例输入
console.log(getCorrespondingValue("5.000"));      // 输出200
console.log(getCorrespondingValue("24.999"));    // 输出200
console.log(getCorrespondingValue("25.000"));    // 输出200
console.log(getCorrespondingValue("25.001"));    // 输出375
console.log(getCorrespondingValue("99.999"));    // 输出375
console.log(getCorrespondingValue("100.000"));   // 输出375
console.log(getCorrespondingValue("100.001"));   // 输出750
console.log(getCorrespondingValue("199.999"));   // 输出750
console.log(getCorrespondingValue("200.000"));   // 输出750
console.log(getCorrespondingValue("200.001"));   // 输出900
console.log(getCorrespondingValue("399.999"));   // 输出900
console.log(getCorrespondingValue("400.000"));   // 输出900
console.log(getCorrespondingValue("400.001"));   // 输出900

// 数字输入同样有效
console.log(getCorrespondingValue(5000));        // 输出200
console.log(getCorrespondingValue(25001));       // 输出375
console.log(getCorrespondingValue(400001));      // 输出900

说明

  • 支持两种输入格式:直接传入数字,或传入带千分点分隔的字符串(如"25.000"会被转换为25000)。
  • 若输入为负数或非数值,函数会抛出错误,可根据需求调整错误处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:48:22