Generate random number between two numbers in JavaScript
Is there a way to generate a random number in a specified range with JavaScript ?
For example: a specified range from 1 to 6 were the random number could be either 1, 2, 3, 4, 5, or 6.
Is there a way to generate a random number in a specified range with JavaScript ?
For example: a specified range from 1 to 6 were the random number could be either 1, 2, 3, 4, 5, or 6.
先自己寫寫看怎麼答,再往下對照重點答案。只存在你這台瀏覽器。
If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:
const rndInt = Math.floor(Math.random() * 6) + 1
console.log(rndInt)
Where:
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
const rndInt = randomIntFromInterval(1, 6);
console.log(rndInt);
What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.
Returns an Integer Random Number between min (included) and max (included):
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Returns Any Random Number between min (included) and max (not included):
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
Useful Examples (Integers):
// 0 -> 10
const rand1 = Math.floor(Math.random() * 11);
// 1 -> 10
const rand2 = Math.floor(Math.random() * 10) + 1;
// 5 -> 20
const rand3 = Math.floor(Math.random() * 16) + 5;
// -10 -> (-2)
const rand4 = Math.floor(Math.random() * 9) - 10;
console.log(rand1);
console.log(rand2);
console.log(rand3);
console.log(rand4);
** And always nice to be reminded (Mozilla):
Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely, the window.crypto.getRandomValues() method.