推荐答案
// www.javascriptcn.com code example
function findMaxAndMin(numbers) {
if (!numbers || numbers.length === 0) {
return { max: undefined, min: undefined };
}
const max = Math.max(...numbers);
const min = Math.min(...numbers);
return { max, min };
}
// 示例
const numbers = [3, 1, 4, 1, 5, 9, 2, 6];
const result = findMaxAndMin(numbers);
console.log("最大值:", result.max); // 输出: 最大值: 9
console.log("最小值:", result.min); // 输出: 最小值: 1
const emptyArrResult = findMaxAndMin([]);
console.log(emptyArrResult) // 输出: {max: undefined, min: undefined}
const nullResult = findMaxAndMin(null);
console.log(nullResult) // 输出: {max: undefined, min: undefined}本题详细解读
Math.max() 和 Math.min() 是 JavaScript 中用于获取一组数值中最大值和最小值的内置方法。它们都接受零个或多个数值参数,并返回其中的最大值或最小值。
1. 基本用法:
Math.max(value1, value2, ..., valueN): 返回 value1, value2, ..., valueN 中的最大值。Math.min(value1, value2, ..., valueN): 返回 value1, value2, ..., valueN 中的最小值。
console.log(Math.max(1, 5, 2, 8, 3)); // 输出: 8 console.log(Math.min(1, 5, 2, 8, 3)); // 输出: 1
2. 处理数组:
当需要从数组中获取最大值和最小值时,可以使用扩展运算符 (...) 将数组展开为单独的参数传递给 Math.max() 和 Math.min()。
const numbers = [3, 1, 4, 1, 5, 9, 2, 6]; const max = Math.max(...numbers); const min = Math.min(...numbers); console.log(max); // 输出: 9 console.log(min); // 输出: 1
3. 处理空数组或 null:
当 Math.max() 或 Math.min() 不接收任何参数(例如,处理空数组),或者接收到 null 或 undefined 时,Math.max() 返回 -Infinity, Math.min() 返回 Infinity。为了逻辑严谨,通常需要在处理数组前进行边界检查。
console.log(Math.max()); // 输出: -Infinity console.log(Math.min()); // 输出: Infinity console.log(Math.max(...[])); // 输出: -Infinity console.log(Math.min(...[])); // 输出: Infinity
4. NaN 的处理:
如果传入的参数中包含 NaN,则 Math.max() 和 Math.min() 会返回 NaN。
console.log(Math.max(1, 2, NaN, 4)); // 输出: NaN console.log(Math.min(1, 2, NaN, 4)); // 输出: NaN
5. 函数实现:
上述示例代码 findMaxAndMin 展示了如何编写一个函数来处理数组,并同时返回最大值和最小值。该函数增加了边界情况的处理,使得代码更加健壮。