Help me with algorithm.. Javascript
On my page I'm making ajax-request to get data from server. The data is list of JSON objects..
Every object has name, 开发者_开发技巧description and datetime. How can I get the object which is the closer to my real data in browser...
Example:
$(json).each(
function(i) {
alert(json.datetime)
//here have to be some algorithm to comparing the time with my current time instead of alert..
});
It sounds like you simply need to loop over each element and compare the date times, storing the current element if it's closer than the last element you compared.
This assumes your json
array contains at least one element, and that your datetime
fields are standard Unix timestamps.
var closest = json[0];
var current = Date.getTime() / 1000; // current datetime, in seconds since epoch
// start at the 2nd element
for (i = 1; i < json.length; ++i) {
if (current - json[i].datetime < current - closest.datetime) {
closest = current;
}
}
Quite often, the UTC timestamps returned through JSON queries are in an ISO 8601 format (e.g. as returned by the JSON interface to the MediaWiki software that powers Wikipedia). Before performing date arithmetic, you will need to convert that to a format that the web browser will recognize.
(See Problem with date formats in JavaScript with different browsers for how to do this using regular expressions.)
Then you will need to subtract that time (new Date(timeString.replace(...)...)
) from the current time (new Date()
). That will give you the interval between the two times in milliseconds (1 second = 1000 milliseconds).
Be aware that this is affected by the accuracy of the client computer's system clock, which you have no control over if you are operating a public web site. If this is the case, you should compare times on your server or at least allow your server to send the accurate time to the client over JSON.
There is my version made from meagar's Answer... Thanks a lot!!!
$(json).each( function(i) {
if (Math.abs(cur_time - time) < Math.abs(cur_time - closest)) {
closest = time;
current_pk=pk;
}
}
}
);
精彩评论