如何在 JavaScript 中找到数组的最大值?
我们可以使用 Math.max() 和 sort() 函数找到数组的最大值。
1) Math.max()
Math.max() 函数通常获取数组中的所有元素,并仔细检查每个值以获取最大值。其方法在下面的示例中进行了讨论。
示例
<html>
<body>
<script>
function maximum(value) {
if (toString.call(value) !== "[object Array]")
return false;
return Math.max.apply(null, value);
}
document.write(maximum([6,39,55,1,44]));
</script>
</body>
</html>输出
55.
2) sort()
使用 sort 和 compare 函数,我们可以按降序或升序排列数组中的元素,然后使用 length 属性找到所需的值。
示例
<html>
<body>
<input type ="button" onclick="myFunction()" value = "clickme">
<p id="max"></p>
<script>
var numbers = [6,39,55,1,44];
document.getElementById("max").innerHTML = numbers;
function myFunction() {
numbers.sort(function(a, b){return a - b});
document.getElementById("max").innerHTML = numbers;
document.write(numbers[numbers.length-1]);
}
</script>
</body>
</html>从上面的程序中,输出显示为以下图像

输出
稍后点击上面的“点击我”按钮,最大值将显示为以下内容
55
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP