如何在 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

更新于: 2019年7月30日

1K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.