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