Có 2 cách phổ biến: dùng Math.max() hoặc sort().
1) Math.max()
Áp dụng Math.max.apply(null, mảng) để tìm max.
Ví dụ
<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>
Kết quả
55
2) sort()
Sắp xếp mảng tăng dần, lấy phần tử cuối.
Ví dụ
<html> <body> <input type="button" onclick="myFunction()" value="click me"> <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>
Kết quả
55