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