- 数学関数(Math) -
Mathオブジェクト
高度な計算にはMathオブジェクトの数学関数を使用します。
■プロパティ
| PI | 円周率 | a = Math.PI; | 3.141... |
|---|
■メソッド
| abs() | 絶対値 | a = Math.abs(-100); | 100 |
|---|---|---|---|
| ceil() | 切り上げ | a = Math.ceil(100.4); | 101 |
| floor() | 切り捨て | a = Math.floor(100.4); | 100 |
| max() | 最大値を返す | a = Math.max(1,8,3); | 8 |
| min() | 最小値を返す | a = Math.min(1,8,3); | 1 |
| pow() | べき乗 | a = Math.pow(4,2); | 16(=4の2乗) |
| random() | 乱数を発生させる | a = Math.random(); | 0以上1未満の実数を発生させる |
| round() | 小数点以下を丸める | a = Math.round(100.4); | 100 |
| sqrt() | 平方根 | a = Math.sqrt(25); | 5 |
→random()・・・0〜0.9999・・・・までの乱数を発生させる。
→round()・・・0〜4は切捨て。5〜9は切上げになる。
■random()の使い方
a = Math.random();//これだとただ乱数が発生するだけなので、
<<0〜9までの整数を取り出す>>
<script type="text/javascript">
a = Math.floor(Math.random() * 10);
alert(a);
</script>
<<0を含まない1〜10までの整数を取り出す>>
<script type="text/javascript">
a = Math.floor(Math.random() * 10) + 1;
alert(a);
</script>
背景色の変更
floorとrandomを使ってページを開いた時に背景色を変更出来る
<script type="text/javascript">
col = new Array();//colと言う名前の空の配列を作る
col[0] = "red";//その箱にそれぞれ色を入れる
col[1] = "blue";
col[2] = "yellow";
col[3] = "green";
a = Math.floor(Math.random() * col.length);
//col.lengthで配列の要素数が取れる。この場合は4
document.bgColor = col[a];
</script>
※col.length配列をいくつ作ったかが分かる。作った配列分を乱数にかけて整数を取り出す。
画像の変更
floorとrandomを使ってページを開いた時に背景色を変更出来る
<script type="text/javascript">
change = new Array();
change[0] = "img00.jpg";
change[1] = "img01.jpg";
change[2] = "img02.jpg";
n = Math.floor(Math.random()*change.length);
document.write("<img src='"+change[n]+"' alt='一部抜粋'>");
</script>