Math.max与min
默认返回值
var min = Math.min(); var max = Math.max(); console.log(min,max);//-Infinity,Infinity
以最大值为例,最小值同理
1.遍历比较
var arr = [6, 4, 1, 8, 2, 11, 23]; var result = arr[0]; for (var i = 1; i < arr.length; i++) { result = Math.max(result, arr[i]); } console.log(result);
2.reduce比较
var arr = [6, 4, 1, 8, 2, 11, 23]; function max(prev, next) { return Math.max(prev, next); } console.log(arr.reduce(max));
3.排序比较
var arr = [6, 4, 1, 8, 2, 11, 23]; arr.sort(function(a,b){return a - b;}); console.log(arr[arr.length - 1])
4.eval调动参数
ar arr = [6, 4, 1, 8, 2, 11, 23]; var max = eval("Math.max(" + arr + ")"); console.log(max)
5.apply传参数
var arr = [6, 4, 1, 8, 2, 11, 23];
console.log(Math.max.apply(null, arr))
6.es6展开
var arr = [6, 4, 1, 8, 2, 11, 23]; console.log(Math.max(...arr))