如何基于数值范围检索JavaScript对象的对应值?
基于数值范围检索对象对应值的解决方案
实现思路
- 将对象的字符串键转换为数值阈值,与对应值组成条目数组。
- 按阈值从小到大排序条目数组,确保按顺序匹配范围。
- 对输入值,找到第一个大于等于它的阈值并返回对应值;若输入超过所有阈值,则返回最后一个条目对应的数值。
代码实现
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
相关产品推荐
相关产品推荐

