JavaScript の Math オブジェクト
Math 數(shù)學(xué)オブジェクト
Math オブジェクトは靜的オブジェクトです。つまり、Math オブジェクトを使用する場(chǎng)合、インスタンスを作成する必要はありません。
Math.PI: 円周率。
Math.abs(): 絶対値。例: Math.abs(-9) = 9
Math.ceil(): 切り上げます (整數(shù)に 1 を追加し、小數(shù)點(diǎn)を削除します)。例: Math.ceil(10.2) = 11
Math.floor(): 切り捨てます (小數(shù)點(diǎn)以下を直接削除します)。例: Math.floor(9.888) = 9
Math.round(): 丸め。例: Math.round(4.5) = 5; Math.round(4.1) = 4
Math.pow(x,y): x の y 乗を求めます。例: Math.pow(2,3) = 8
Math.sqrt(): 平方根を求めます。例: Math.sqrt(121) = 11
Math.random(): 0 から 1 までのランダムな 10 進(jìn)數(shù)を返します。例: Math.random() = 0.12204467732259783
注: (最小値、最大値) の間の亂數(shù)を検索します。式は次のとおりです: Math.random()*(max-min)+min
例: 0 ~ 10 のランダムな整數(shù)を検索します。 20 ~ 30 のランダムな整數(shù)を検索します。 7 から 91 までの整數(shù)
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> //求兩個(gè)整數(shù)之間的隨機(jī)整數(shù) //定義隨機(jī)數(shù)的函數(shù) function getRandom(min,max){ //求隨機(jī)數(shù) var random =Math.random()*(max-min)+min; //向下取整 random = Math.floor(random); //輸出結(jié)果 document.write(random+"<hr>"); } //調(diào)用函數(shù) getRandom(0,100); getRandom(5,89); getRandom(100,999); </script> </head> <body> </body> </html>
例: ランダムな Web ページの背景色
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> </head> <body> </body> </html> <script> var min = 100000; var max = 999999; var random = Math.random() *(max-min)+min; //向下取整 random = Math.floor(random); document.body.bgColor = "#"+random; </script>