这是执行此操作的函数。它希望用于具有数字键的对象,例如您的数组:
function getClosestKey(arr, target, u){
if(arr.hasOwnProperty(target))
return target;
var keys = Object.keys(arr);
keys.sort(function(a,b){ return a-b; });
// Can replace linear scan with Binary search for O(log n) search
// If you have a lot of keys that may be worthwhile
for(var i = 0, prev; i < keys.length; i++){
if(keys[i] > target)
return prev === u ? u : +prev;
prev = keys[i];
}
return +keys[i - 1];
}
您必须在旧浏览器中使用 SHIM Object.keys:
Object.keys = Object.keys || function(obj){
var result = [];
for(var key in obj)
if(obj.hasOwnProperty(key)) result.push(key);
return result;
}
用法:
var price_array = [];
price_array[1] = 39.99;
price_array[5] = 24.99;
price_array[10] = 19.99;
getClosestKey(price_array, 0); // undefined
getClosestKey(price_array, 1); // 1
getClosestKey(price_array, 3); // 1
getClosestKey(price_array, 4); // 1
getClosestKey(price_array, 5); // 5
getClosestKey(price_array, 7); // 5
getClosestKey(price_array, 9); // 5
getClosestKey(price_array, 10); // 10
getClosestKey(price_array, 100); // 10