可以使用 JavaScript 中的 Math 对象来求一个数组中的最大值和最小值。具体方法如下:
let arr = [4, 12, 6, 8, 2, 10];
let max = Math.max(...arr);
let min = Math.min(...arr);
console.log(max); // 输出 12
这里使用了 ES6 中的扩展运算符(...)来将数组展开成参数序列,传递给 Math.max() 和 Math.min() 方法。您也可以使用 apply() 方法来传递参数序列。
let arr = [4, 12, 6, 8, 2, 10];
let max = Math.max.apply(null, arr);
let min = Math.min.apply(null, arr);
console.log(max); // 输出 12
console.log(min); // 输出 2
注意,当数组为空时,Math.max() 和 Math.min() 方法都会返回 Infinity。可以在使用这些方法前,对数组进行非空判断。