js获取数组中的最小值和最大值的几种方法

js获取数组中的最小值和最大值的几种方法

js获取数组中的最小值和最大值的几种方法。

Math.max()配合扩展符

1
2
3
let nums = [1, 6, 2, 8, 10, 11, 24, 3, 9];
let max = Math.max(...nums);
let min = Math.min(...nums);

Math.max()配合apply()

1
2
3
let nums = [1, 6, 2, 8, 10, 11, 24, 3, 9];
let max = Math.max.apply(Math, nums); // 24
let min = Math.min.apply(Math, nums); // 1

Math.max()配合reduce()

1
2
3
4
5
6
7
let nums = [1, 6, 2, 8, 10, 11, 24, 3, 9];
let max = nums.reduce(function(prev, cur) {
return Math.max(prev, cur);
});
let min = nums.reduce(function(prev, cur) {
return Math.min(prev, cur);
});

sort()排序

1
2
3
4
5
6
let nums = [1, 6, 2, 8, 10, 11, 24, 3, 9];
nums.sort(function(a, b) {
return a - b;
});
let min = nums[0];
let max = nums[nums.length - 1];

评论