这样的事情应该比排序更快(取决于数据):
/*
values: array of values to test.
fn: function that takes two arguements and returns true if the first is bigger.
*/
var maximum = function(values, fn) {
var currentValue, maxValue = values.pop();
while(values.length)
maxValue = fn(maxValue, currentValue = values.pop()) ? maxValue : currentValue;
return maxValue;
}
示例:http: //jsfiddle.net/SaBJ4/2/
更好的是,使用Array.reduce
:
var a = ['abc', 'defg', 'highlkasd', 'ac', 'asdh'];
a.reduce(function(a, b) { return a.length > b.length ? a : b; }); // highlkasd