您的位置:首页 > 其它

如何确定一个数组中的最大值

2015-08-29 18:27 316 查看
今天面试的一道题目是这样的,假设有一个数组,求出数组中的最大值,我使用的方法是:

var a = [3, 10, 5, 8, 12, 15];

function compare(value1, value2) {
if (value1 > value2) {
return -1;
} else if (value1 < value2) {
return 1;
} else {
return 0;
}
}
a.sort(compare);
console.log(a[0]);


后面一想,可以这样精简代码:

var a = [3, 10, 5, 8, 12, 12, 15];

function compare(value1, value2) {
return value2 - value1; //此时是降序        //value1 - value2 是升序
}
a.sort(compare);
console.log(a[0]);


今天看书看到Math对象里面,看到了一种以最快的方式求出这个数组中的最大值

var a = [3, 10, 5, 8, 12, 12, 15];

var max = Math.max.apply(Math,a); //注意把第一个参数设置成为Math

console.log(max);

如此以来的话就方便很多了。而且通过Math对象提供的计算功能执行起来是最快的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: