可以使用 Math.max() 方法来找出数组中的最大值。

例如:

let arr = [1, 2, 3, 4, 5];
let max = Math.max(...arr);
console.log(max); // 输出 5

另外,也可以使用 for 循环遍历数组,通过比较的方式找出最大值,如下所示:

let arr = [1, 2, 3, 4, 5];
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
  if (arr[i] > max) {
    max = arr[i];
  }
}
console.log(max); // 输出 5
JavaScript 数组最大值:两种方法详解

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

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