js では Math(算数)オブジェクトを使用して乱数を生成できます。
知っておくべき Math オブジェクトのメソッド
| メソッド | 説明 |
|---|---|
| ceil(x) | 数値を上方向に丸めます。つまり切り上げです。 | floor(x) | x を下方向に丸めます。つまり切り捨てです。 |
| round(x) | 四捨五入。 |
| random() | 0 〜 1 の間の乱数を返します。0 を含み、1 は含みません。 |
いくつかの例の説明:
Math.ceil(Math.random()*10); // 获取从 1 到 10 的随机整数,取 0 的概率极小。 Math.round(Math.random()); // 可均衡获取 0 到 1 的随机整数。 Math.floor(Math.random()*10); // 可均衡获取 0 到 9 的随机整数。 Math.round(Math.random()*10); // 基本均衡获取 0 到 10 的随机整数,其中获取最小值 0 和最大值 10 的几率少一半。
結果は 0〜0.4 が 0、0.5〜1.4 が 1、8.5〜9.4 が 9、9.5〜9.9 が 10 になるため、先頭と末尾の分布区間は他の数字の半分だけになります。
[n,m] のランダムな整数を生成
関数の機能:生成[n,m]のランダムな整数。
js で認証コードを生成したり、選択肢をランダムに選んだりするときに便利です。
//生成从minNum到maxNum的随机数
function randomNum(minNum,maxNum){
switch(arguments.length){
case 1:
return parseInt(Math.random()*minNum+1,10);
break;
case 2:
return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10);
break;
default:
return 0;
break;
}
}
プロセス分析:
Math.random() は [0,1) の数を生成するので、Math.random()*5 は {0,5) の数を生成します。
通常は整数を期待するので、得られた結果を少し処理する必要があります。
parseInt()、Math.floor()、Math.ceil()、Math.round() はすべて整数を得られます。
parseInt() と Math.floor() の結果はどちらも切り捨てです。
したがって、Math.random()*5 で生成されるものはすべて [0,4] のランダムな整数です。
したがって、[1,max] の乱数を生成する式は次のとおりです:
// max - 期望的最大值 parseInt(Math.random()*max,10)+1; Math.floor(Math.random()*max)+1; Math.ceil(Math.random()*max);
したがって、[0,max] から任意の数までの乱数を生成する式は次のとおりです:
// max - 期望的最大值 parseInt(Math.random()*(max+1),10); Math.floor(Math.random()*(max+1));
したがって、[min,max] の乱数を生成したい場合の式は次のとおりです:
// max - 期望的最大值 // min - 期望的最小值 parseInt(Math.random()*(max-min+1)+min,10); Math.floor(Math.random()*(max-min+1)+min);
例
// ユーザー入力
const min = parseInt(prompt("最小値を入力: "));
const max = parseInt(prompt("最大値を入力: "));
// 乱数を生成
const a = Math.floor(Math.random() * (max - min + 1)) + min;
// 乱数を表示
document.write(`${min}〜 ${max}の乱数:${a}`);
const min = parseInt(prompt("最小値を入力: "));
const max = parseInt(prompt("最大値を入力: "));
// 乱数を生成
const a = Math.floor(Math.random() * (max - min + 1)) + min;
// 乱数を表示
document.write(`${min}〜 ${max}の乱数:${a}`);
試してみる »
オンラインの乱数生成器:https://c.example.com/front-end/6680/
原文リンク:http://www.cnblogs.com/starof/p/4988516.html