- 整数部のみを保持する(小数部分は廃棄されます)
parseInt(5.1234); // 5
- 切り捨て(としての最大の整数<=数値、とのparseInt())
Math.floor(5.1234); // 5
- (10進整数部分と+1まで)切り上げ
Math.ceil(5.1234); // 6
- 丸め(小数部)
Math.round(5.1234); // 5
Math.round(5.6789); // 6
- 絶対値
Math.abs(-1); // 1
- 2つの数値のうち大きい方を返します。
Math.max(1,2); // 2
- 小さい方の2つの数値を返します。
Math.min(1,2); // 1
- 乱数(0-1)
Math.random(); //返回 0(包括) 至 1(不包括) 之间的随机数
JavaScriptのランダムな整数
一緒に使用Math.random()とMath.floor()はランダムな整数を返します。
Math.floor(Math.random() * 10); // 返回 0 至 9 之间的数
Math.floor(Math.random() * 11); // 返回 0 至 10 之间的数
Math.floor(Math.random() * 100); // 返回 0 至 99 之间的数
Math.floor(Math.random() * 101); // 返回 0 至 100 之间的数
Math.floor(Math.random() * 10) + 1; // 返回 1 至 10 之间的数
Math.floor(Math.random() * 100) + 1; // 返回 1 至 100 之间的数
適切なランダム関数
あなたは上記の例からわかるように、ランダム関数は、すべてのランダムな整数を生成するために使用されて作成することは良いアイデアです。
このJavaScript関数は、常に(を含む)minとmax(含まれていない)との間の乱数を返します。
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
このJavaScript関数は常に間の最小値と最大値(両方を含む)の間の乱数を返します。
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}