1οΈβ£ Math.random()
0 ≤ x οΌ1 ꡬκ°μμ λΆλμμμ μ λμλ₯Ό μμ±ν μ μλ€.
[Javascript] Math λ©μλ (+μμ±)
2οΈβ£ νΉμ λ²μ λ΄μ λμλ₯Ό μμ±νλ λ°©λ²
min ≤ λμοΌmax
*minμ΄ μ μκ° μλ κ²½μ°μλ minλ³΄λ€ ν° μ΅μμ μ μ
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
3οΈβ£ μ μ λμλ₯Ό μμ±νλ λ°©λ²
Math.random() (λμ μμ± ν¨μ)μ Math.floor(x) (λ²λ¦Ό ν¨μ)λ₯Ό ν¨κ» μ¬μ©νλ€
νΉμ λ²μ λ΄μ μ μ λμλ₯Ό μμ±νλ λ°©λ²
min ≤ μ μ λμοΌmax
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //μ΅λκ°μ μ μΈ, μ΅μκ°μ ν¬ν¨
}
νΉμ λ²μ λ΄μ μ μ λμλ₯Ό μμ±νλ λ°©λ² (μ΅λκ° ν¬ν¨)
min ≤ μ μ λμ≤max
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //μ΅λκ°λ ν¬ν¨, μ΅μκ°λ ν¬ν¨
}
μμ
// 0 <= random <= 9
Math.floor(Math.random() * 10); //3
// 0 <= random <= 10
Math.floor(Math.random() * 11); //7
// 0 <= random <= 99
Math.floor(Math.random() * 100); //87
// 0 <= random <= 100
Math.floor(Math.random() * 101); //71
// 1 <= random <= 10
Math.floor(Math.random() * 10) + 1; //4
// 2 <= random <= 5
Math.floor(Math.random() * 4) + 2; //4