我的尝试:
var objects = [
{"min":"0","max":"50","name":"name1"},
{"min":"50","max":"100","name":"name2"},
{"min":"100","max":"150","name":"name3"}
];
var value = 40;
objects.forEach(function(item, i){
if(Number(item.min) >= value && value <= Number(item.max) ){
console.log("name is ", item.name );
}
});
将控制台设为:
name is name2
name is name3
但我期望name is name2
通过方案获取范围值的正确方法是什么?
答案 0 :(得分:2)
移动value
变量,以便检查它是否大于或等于min,否则你要检查min是否大于或等于value
: -
let objects = [
{"min":"0","max":"50","name":"name1"},
{"min":"50","max":"100","name":"name2"},
{"min":"100","max":"150","name":"name3"}
];
let value = 40;
objects.forEach(function(item, i){
if (value >= Number(item.min) && value <= Number(item.max)) {
console.log("name is ", item.name );
}
});
&#13;
答案 1 :(得分:2)
使用Array#find
方法:
var objects = [
{"min":"0","max":"50","name":"name1"},
{"min":"50","max":"100","name":"name2"},
{"min":"100","max":"150","name":"name3"}
];
var value = 90;
let res = objects.find(obj => Number(obj.min) <= value && value <= Number(obj.max));
console.log(res ? res.name : 'Not found');
答案 2 :(得分:1)
我们走了,你只需要交换变量:
if(Number(item.min) >= value && value <= Number(item.max) ){
if(value >= Number(item.min) && value <= Number(item.max) ){
var objects = [
{"min":"0","max":"50","name":"name1"},
{"min":"50","max":"100","name":"name2"},
{"min":"100","max":"150","name":"name3"}
];
var value = 40;
objects.forEach(function(item, i){
if(value >= Number(item.min) && value <= Number(item.max) ){
console.log("name is ", item.name );
}
});
答案 3 :(得分:0)
如果范围增加50,则根本不需要迭代。我们将value
除以50
并向下舍入,为我们提供索引。
const index = n && Math.floor(n/50) - !(n%50);
x1
到x50
的任何范围都在较低的范围内,因此会处理150
之类的值。 0
值包含在第一个范围内。
var objects = [
{"min":"0","max":"50","name":"name1"},
{"min":"50","max":"100","name":"name2"},
{"min":"100","max":"150","name":"name3"}
];
test(0);
test(10);
test(50);
test(51);
test(100);
test(149);
test(150);
test(151);
function test(n) {
const index = n && Math.floor(n/50) - !(n%50);
const res = objects[index];
console.log("value:", n, ", item:", res ? res.name : 'Not found');
}