JavaScript中取数组最大值的方法

分类:知识百科 日期: 点击:0

有很多,比如可以使用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()方法
标签:

版权声明

1. 本站所有素材,仅限学习交流,仅展示部分内容,如需查看完整内容,请下载原文件。
2. 会员在本站下载的所有素材,只拥有使用权,著作权归原作者所有。
3. 所有素材,未经合法授权,请勿用于商业用途,会员不得以任何形式发布、传播、复制、转售该素材,否则一律封号处理。
4. 如果素材损害你的权益请联系客服QQ:77594475 处理。