可以使用 Math.max() 函数来获取最大值。

例如,取三个数的最大值:

let a = 10;
let b = 20;
let c = 15;

let max = Math.max(a, b, c);
console.log(max); // 20

如果要取一个数组中的最大值,可以使用 apply() 方法将数组作为参数传递给 Math.max() 函数:

let nums = [10, 20, 15, 30, 25];

let max = Math.max.apply(null, nums);
console.log(max); // 30

从 ES6 开始,还可以使用展开运算符(...)来取数组中的最大值:

let nums = [10, 20, 15, 30, 25];

let max = Math.max(...nums);
console.log(max); // 30
JavaScript 获取最大值方法详解 - Math.max() 函数使用指南

原文地址: https://www.cveoy.top/t/topic/nCU2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录