假设
var times = {
"1367999303810": { // today at 9:48am
"item1": "val1",
"item2": "val2"
},
"1368000000000": { // today at 10am
"item1": "val3",
"item2": "val4"
}
}
我会编写这样的代码(请修正数学!)
现场演示
function getNearest(findTime) {
for (var i=0;i<tArr.length;i++) {
window.console && console.log(new Date(findTime),new Date(tArr[i]))
if (findTime === tArr[i]) return findTime; // exact match
if (findTime >= tArr[i]) break; // pinpoint
}
if (i==tArr.length) return -1; // nothing found
if (i==tArr.length-1) return tArr[i]; // found the end
// here the time to find is greater than one of the array entries
var diff1 = Math.abs (findTime - tArr[i]), // distance from last entry
diff2 = Math.abs (tArr[i+1] - findTime); // distance to next entry
return diff1 === diff2 ? tArr[i+1] : // return the newest time
diff2 > diff1 ? tArr[i] : tArr[i+1]; // or the nearest
}
var tArr = [];
for (var t in times) tArr.push(parseInt(t));
tArr.sort();
var findTime = new Date(2013,4,8,9,50,0).getTime(); // today at 9:50
var time = getNearest(findTime);
if (time !=-1) window.console && console.log(times[time])