如何按最近的范围值查找对象名称?

时间:2017-10-06 12:26:33

标签: javascript jquery

我的尝试:

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通过方案获取范围值的正确方法是什么?

4 个答案:

答案 0 :(得分:2)

移动value变量,以便检查它是否大于或等于min,否则你要检查min是否大于或等于value : -

&#13;
&#13;
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;
&#13;
&#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);

x1x50的任何范围都在较低的范围内,因此会处理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');
}