当需要在一个数组中找到最大值和最小值的时候,可以使用以下两个方法:Math.max()
和 Math.min()
。
Math.max()
该方法用于寻找一组数字中的最大值。语法如下:
Math.max([value1], [value2], ..., [valueN])
注意,Math.max()
方法不接受数组作为参数,而是一系列的数字参数。如果需要寻找一个数组中的最大值,需要使用以下方式:
const arr = [1, 9, 3, 7, 5];
const max = Math.max.apply(null, arr);
console.log(max); // 9
在这个例子中,我们使用 apply()
方法来将数组作为参数传递给 Math.max()
方法,并得到了最大值。
Math.min()
与 Math.max()
方法类似,该方法用于寻找一组数字中的最小值。语法如下:
Math.min([value1], [value2], ..., [valueN])
同样地,如果需要寻找一个数组中的最小值,需要使用以下方式:
const arr = [1, 9, 3, 7, 5];
const min = Math.min.apply(null, arr);
console.log(min); // 1
在这个例子中,我们使用 apply()
方法来将数组作为参数传递给 Math.min()
方法,并得到了最小值。
需要注意的是,以上两个方法都不会改变原始的数组,它们只会返回最大或最小的值。
示例1:
const arr = [1, 2, 3, 4, 5];
const max = Math.max.apply(null, arr);
const min = Math.min.apply(null, arr);
console.log(max); // 5
console.log(min); // 1
示例2:
const arr = [6, 2, 8, 3, 10];
const max = Math.max.apply(null, arr);
const min = Math.min.apply(null, arr);
console.log(max); // 10
console.log(min); // 2
综上所述,使用 Math.max()
和 Math.min()
可以很方便地寻找一个数组中的最大值和最小值。