我有一个时间阵列,
var arr= ["17:30:48","19:30:48","18:30:48","19:30:48","17:40:48","19:10:48","17:10:48","19:30:45","17:13:48","19:13:48","17:30:48","19:28:48"];
我想从这些中获得最短和最长时间。尝试了,但是它变得冗长。它有任何简单的方法去做。
答案 0 :(得分:1)
看看这个小提琴:http://jsfiddle.net/99Eue/12/
使用此排序功能并抓住第一个元素。这将为您带来最大的收益。
arr.sort(function (a,b) {
if(a > b) { return -1; }
if(a < b) { return 1; }
return 0;
});
Console.log(arr[0]);
希望这有帮助。
答案 1 :(得分:1)
var min = function(arr) {
return arr.reduce(function(a, b) { return a <= b? a : b;});
};
var max = function(arr) {
return arr.reduce(function(a, b) { return a <= b? b : a;});
};
reduce
速度更快,但可能更好地使用旧的array.sort
来提高可读性
答案 2 :(得分:0)
var arr= ["17:30:48","19:30:48","17:27:48","19:30:48","17:30:48","19:30:48","17:30:48","19:30:48","17:30:48","19:30:48","17:30:48","19:30:48"];
arr.sort(function (a, b) {
return new Date('1970/01/01 ' + a) - new Date('1970/01/01 ' + b);
});
alert("Min: " + arr[0] + " Max: " + arr[arr.length-1]);