This question already has answers here:
Find the min/max element of an Array in JavaScript
(53个答案)
3年前关闭。
给定一个值数组
我知道我可以编写一个循环并跟踪最大值,但是我正在寻找一种使用JavaScript语法的更具代码效率的方式。
(53个答案)
3年前关闭。
给定一个值数组
[1,2,0,-5,8,3]
,如何获取JavaScript中的最大值?我知道我可以编写一个循环并跟踪最大值,但是我正在寻找一种使用JavaScript语法的更具代码效率的方式。
最佳答案
您可以使用 Math.max
和ES6 spread syntax ( ...
):
let array = [1, 2, 0, -5, 8, 3];
console.log(Math.max(...array)); //=> 8