clover.blue

[JS講座] 12. 数学関数(Math)で演算

Data
2019/07/28
Tag

0以上1未満の乱数を返す

Math.random();

console.log(Math.random());

/*
表示結果
0.40883730142377317のような乱数
*/

引数の中から一番大きな値を返す

Math.max();

console.log(Math.max(1, 2, 3, 6, 4, 5));

/*
表示結果
6
*/

引数の中から一番小さな値を返す

Math.min();

console.log(Math.min(1, 2, 3, 6, 4, 5));

/*
表示結果
1
*/

小数点以下を切り捨てた整数を返す

Math.floor(1.1);

console.log(Math.floor(Math.random() * 3));

/*
表示結果
整数 0 〜 2
*/

小数点以下を繰り上げした整数を返す

Math.ceil(0.1);

console.log(Math.ceil(Math.random() * 3));

/*
表示結果
整数 1 〜 3
*/

小数点以下を四捨五入した整数を返す

Math.round(0.1);

console.log(Math.round(Math.random() * 3));

/*
表示結果
整数 0 〜 3
*/