有很多,比如可以使用Math.max()方法,也可以使用Math.min()方法,或者使用Array.prototype.sort()方法。
1. 使用Math.max()方法
Math.max()方法可以用来求数组的最大值,它接受一个可变参数,并返回这些参数中最大的值。例如:
var arr = [3, 5, 7, 2, 9]; var maxValue = Math.max.apply(null, arr); console.log(maxValue); // 9
2. 使用Math.min()方法
Math.min()方法可以用来求数组的最小值,它接受一个可变参数,并返回这些参数中最小的值。例如:
var arr = [3, 5, 7, 2, 9]; var minValue = Math.min.apply(null, arr); console.log(minValue); // 2
3. 使用Array.prototype.sort()方法
Array.prototype.sort()方法可以用来求数组的最大或最小值,它接受一个比较函数作为参数,并返回排序后的数组。例如:
var arr = [3, 5, 7, 2, 9]; arr.sort(function(a, b) { return b - a; }); console.log(arr[0]); // 9
可以看到,使用sort()方法求最大值时,只需要把比较函数的返回值改为b-a,即可实现降序排序,从而取出最大的值。
有以下三种:
- 使用Math.max()方法
- 使用Math.min()方法
- 使用Array.prototype.sort()方法