- Home ›
- JavaScript入門 ›
- Mathクラス ›
- HERE
max関数
広告
max関数は引数に指定した複数の値の中で最大の値を返します。
Math.max(val1, val2, ...)
引数の中で最大の値を返します。 パラメータ: val 数値または他の値 戻り値: 引数の中で最大の値
引数に2つ以上の値が指定された場合、その中の最大の値を返します。
Math.max(10, 5) => 10 Math.max(10, 882, 47) => 882
引数に1つだけ値が指定された場合、その値を返します。
Math.max(10) => 10
引数が空だった場合、「-Infinity」を返します。
Math.max() => -Infinity
引数の中にNaNが含まれている場合、または数値以外の値が含まれていてその値を数値に変換した時にNaNとなる場合には、NaNを返します。
Math.max(10, 882, NaN, 47) => NaN
数値以外の値が引数に与えられた場合は数値に変換した上で計算します。
実際の使い方は次の通りです。
var num = Math.max(10, 8, -4, 5);
上記の場合、変数numには8が代入されます。
サンプルコード
では簡単なサンプルで試してみます。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta http-equiv="Content-Script-Type" content="text/javascript"> <title>JavaScript テスト</title> </head> <body> <script type="text/javascript" src="./js/script6_1.js"> </script> </body> </html>
function print(str){ document.write(str + "<br />"); } document.write("<p>"); print("Math.max() = " + Math.max()); print("Math.max(10) = " + Math.max(10)); print("Math.max(10, 3) = " + Math.max(10, 3)); print("Math.max(10, 3, 29) = " + Math.max(10, 3, 29)); print("Math.max(10, '38', 29) = " + Math.max(10, '38', 29)); print("Math.max(10, 'abc', 29) = " + Math.max(10, 'abc', 29)); print("Math.max(10, NaN, 29) = " + Math.max(10, NaN, 29)); document.write("</p>");
上記を実際にブラウザ見てみると次のように表示されます。
( Written by Tatsuo Ikura )