如何可以生成两个指定的变量之间的随机整数在JavaScript中,例如x = 4和y = 8将输出任何的4, 5, 6, 7, 8 ?
x = 4
y = 8
4, 5, 6, 7, 8
There are some examples on the Mozilla Developer Network page:(Mozilla开发人员网络页面上有一些示例:)
/** * Returns a random number between min (inclusive) and max (exclusive) */ function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } /** * Returns a random integer between min (inclusive) and max (inclusive). * The value is no lower than min (or the next integer greater than min * if min isn't an integer) and no greater than max (or the next integer * lower than max if max isn't an integer). * Using Math.round() will give you a non-uniform distribution! */ function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }
Math.random()
Number
[0 .................................... 1)
min
max
[0 .................................... 1) [min .................................. max)
Math.random
[0 .................................... 1) [min - min ............................ max - min)
[0 .................................... 1) [0 .................................... max - min)
Math.random() | [0 .................................... 1) [0 .................................... max - min) | x (what we need)
x
x = Math.random() * (max - min);
x = Math.random() * (max - min) + min;
round
ceil
floor
Math.round(Math.random() * (max - min)) + min
min...min+0.5...min+1...min+1.5 ... max-0.5....max └───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round() min min+1 max
Math.floor(Math.random() * (max - min +1)) + min
min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval) | | | | | | └───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor() min min+1 max-1 max
ceil()
-1
min-1
1.4m articles
1.4m replys
5 comments
57.0k users