Javascript 查找 table

Javascript lookup table

我有一个保存我数据的对象。

 DataSoccer: [{ 0: '0.00', 1: '10.4', 2:'100.5', 3:'15.3', 4:'11.2', 5:'15.9'}]

当键值是完整的时,这很简单。

DataSoccer[0][1] //returns 10.4

问题是索引现在不完整

  DataSoccer: [{ 0: '0.00', 1.30: '10.4', 2.40:'100.5', 3.40:'15.3', 4.5:'11.2', 5:'15.9'}]

所以我得到一个用户输入,比如 2.30 应该 return 10.4(第二个索引)

目前我有一个 if 语句

if (value == 0 {
return 0.00
}
else if (value <= 1.30) {
   return 10.4
}

else if (value > 1.30 value < 2.40) {
   return 100.5
}

正如您想象的那样,使用 if-else 的查找功能会变得非常麻烦,并且想知道是否有更好的方法?

一次迭代取值的解决方法

function getValue(p) {
    return object[Object.keys(object).reduce(function (r, k) {
        return k <= r || k > p ? r: k;
    }, undefined)];
}

var object = { 0: '0.00', 1.30: '10.4', 2.40: '100.5', 3.40: '15.3', 4.5: '11.2', 5: '15.9' };

document.write('<pre>' + JSON.stringify(getValue(2.3), 0, 4) + '</pre>');

这是对以数字为键的对象字面量的注解。

对象的属性是字符串,但在本例中是数字,然后转换为字符串。

var DataSoccer = [{ 0: '0.00', 1.30: '10.4', 2.40:'100.5', 3.40:'15.3', 4.5:'11.2', 5:'15.9'}];
document.write('<pre>' + JSON.stringify(DataSoccer, 0, 4) + '</pre>');
document.write(DataSoccer[0]['2.4']);

试试这个

var DataSoccer =  [{ 0: '0.00', 1.30: '10.4', 2.40:'100.5', 3.40:'15.3', 4.5:'11.2', 5:'15.9'}];

//sort all the keys in DataSoccer[0]
var sortedKeys = Object.keys(DataSoccer[0]).sort(function(a,b){ return parseFloat(a) - parseFloat(b) }); 

//get value lesser than 2.3 which is 1.3
var smallerKey = sortedKeys.filter(function(val){ return val < 2.3}).pop(); 

//get next value which is 2.4 after 1.3
var actualKey = sortedKeys[sortedKeys.indexOf(smallerKey) + 1]; 

//alerting the value at 2.4
alert("value is " + DataSoccer[0][actualKey] ); //access value ar 2.4