3 回答
TA贡献1834条经验 获得超8个赞
简单的代码给你
var ranges = [{"1-10":"Apple"},{"11-20":"Ball"},{"21-30":"Cat"}]
function getAns(input_number) {
let result = null
// handle input ranges
for (let index in ranges) {
for (let key in ranges[index]) {
let min = key.split('-')[0]
let max = key.split('-')[1]
if (input_number >= min && input_number <= max) {
result = ranges[index][key]
}
}
}
return result
}
console.log(getAns(12))
TA贡献1829条经验 获得超7个赞
我会使用过滤器
const getValue = (value, ranges) => {
const res = ranges.filter(obj => {
const [min, max] = Object.keys(obj)[0].split("-");
return value >= +min && value <= +max;
})
return res && res.length > 0 ? Object.values(res[0])[0] : "N/A"
}
const ranges = [{"1-10":"Apple"},{"11-20":"Ball"},{"21-30":"Cat"}]
console.log(getValue(0,ranges))
console.log(getValue(1,ranges))
console.log(getValue(12,ranges))
console.log(getValue(30,ranges))
console.log(getValue(31,ranges))
TA贡献1824条经验 获得超8个赞
尝试
ranges.map(x=> Object.entries(x).flat() ) .find(a=> (a[0]=a[0].split`-`, n>=a[0][0] && n<=a[0][1] && a[1]) )
var ranges = [{"1-10":"Apple"},{"11-20":"Ball"},{"21-30":"Cat"}]
var n=12;
var r = ranges.map( x=>Object.entries(x).flat() )
.find(a=> (a[0]=a[0].split`-`, n>=a[0][0] && n<=a[0][1] && a[1]) )
console.log(r[1]);
添加回答
举报