faker使えばいいが、素で生成するとき用のメモ。
乱数系
基本
まず、乱数発生の基本。
下記で、0 < n < 1で生成されるが、単独だと事実上使いみちはない。
console.log(Math.random());
0.15043077282053852
よく使うのがMath.floor()と合わせて使う。
以下で0〜9までの値が生成される。
console.log(Math.floor(Math.random() * 10));
下記のようにすると、0~4までの値が生成される。
console.log(Math.floor(Math.random() * 5));
0ありは配列操作等のときは便利(後述)だが、一般には1を足すことがお多い。
console.log(Math.floor(Math.random() * 10) + 1);
これで1~10が生成される。
応用
上記を利用してよく利用するのが、
指定範囲の値を生成
例えば15歳から60歳までの値を生成したいときなどは以下のようにする。
console.log(Math.floor(Math.random() * ((60 + 1) - 15)) + 15);
34
一般化すると、
Math.floor(Math.random() * ((max + 1) - min)) + min
という形式となる。
配列の中から値を選ぶ
あとよくあるのが配列の中からランダムに値を選ぶときなど。
下記の場合、gender.length()は2なので0,1が生成される。
const gender = ['女性', '男性'];
console.log(gender[Math.floor(Math.random() * gender.length)]);
女性
(前)0埋め(固定長生成)
おまけですが、生成した値を0埋めして固定長の値にする。
const id = Math.floor(Math.random() * 999) + 1;
console.log(id.toString().padStart(8, "0"));
console.log(id.toString().padEnd(8, "0"));
00000017
17000000
splice使った書き方してましたが、上記の方がモダンというコメントいただきました。そのためのメソッドなので、こちらのほうがいいですね(前埋め、後埋めにも対応できますし)。