max()
方法用于查找指定值中的最大值并返回它。
示例
let numbers = Math.max(12, 4, 5, 9, 0, -3);
console.log(numbers);
// Output: 12
max() 语法
max()
方法的语法是
Math.max(number1, number2,...)
这里,max()
是一个静态方法。因此,我们使用类名 Math
来访问该方法。
max() 参数
max()
方法接受任意数量的参数
-
number1/number2/…
- 要计算最大值的各个值
max() 返回值
max()
方法返回
- 给定数字中的最大值
- 对于非数字参数,返回 NaN (Not a Number)。
示例 1: JavaScript Math.max()
// max() with negative numbers
let numbers1 = Math.max(-1, -11, -132);
console.log(numbers1);
// max() with positive numbers
let numbers2 = Math.max(0.456, 135, 500);
console.log(numbers2);
// Output:
// -1
// 500
在上面的示例中,我们使用 Math.max()
来查找其中的最小值
Math.max(-1,-11,-132)
- 返回 -1Math.max(0.456,135,500)
- 返回 500
示例 2: 数组与 Math.max() 结合使用
let numbers = [4, 1, 2, 55, 9];
// max() with a spread operator
let maxNum = Math.max(...numbers);
console.log(maxNum);
// Output: 55
在上面的示例中,我们创建了一个名为 numbers
的数组。请注意,我们将数组作为参数传递给 Math.max()
方法。
let minNum = Math.max(...numbers);
这里,...
是展开运算符,它会将数组解构并将数组值作为参数传递给 max()
。
然后该方法查找最小值。
示例 3: 非数字参数与 Math.max() 结合使用
// max() with the string argument
let numbers1 = Math.max("Dwayne", 2, 5, 79);
console.log(numbers1);
// max() with character arguments
let maxNum = Math.max('A', 'B', 'C');
console.log(maxNum);
// Output:
// NaN
// NaN
在上面的示例中,我们将 max()
方法与字符串和字符参数一起使用。对于这两个参数,我们都得到了 NaN 作为输出。
另请阅读