Math.random()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itโs been available across browsers since โจ2015๋ 7์โฉ.
Math.random()
์ ์ ๋ฉ์๋๋ 0๋ณด๋ค ํฌ๊ฑฐ๋ 1๋ณด๋ค ์์ ๋ถ๋ ์์์ ์์ฌ ๋์๋ฅผ ๋ฐํํ๋ฉฐ, ํด๋น ๋ฒ์์์ ๊ฑฐ์ ๊ท ์ผํ ๋ถํฌ๋ฅผ ๊ฐ์ง๋ฏ๋ก ์ํ๋ ๋ฒ์๋ก ํ์ฅํ ์ ์์ต๋๋ค. ๊ตฌํ์ฒด๋ ๋์ ์์ฑ ์๊ณ ๋ฆฌ์ฆ์ ์ด๊ธฐ ์๋๋ฅผ ์ ํํ๋ฉฐ, ์ฌ์ฉ์๊ฐ ์ ํํ๊ฑฐ๋ ์ฌ์ค์ ํ ์ ์์ต๋๋ค.
์ฐธ๊ณ :
Math.random()
์ ์ํธํ์ ์ผ๋ก ์์ ํ ๋์๋ฅผ ์ ๊ณตํ์ง ์์ต๋๋ค. ๋ณด์๊ณผ ๊ด๋ จ๋ ์ฉ๋๋ก ์ฌ์ฉํ์ง ๋ง์ธ์. ๋์ Web Crypto API, ๋ ์ ํํ๊ฒ๋window.crypto.getRandomValues()
๋ฉ์๋๋ฅผ ์ฌ์ฉํ์๊ธฐ ๋ฐ๋๋๋ค.
์๋ํด ๋ณด๊ธฐ
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
console.log(getRandomInt(3));
// Expected output: 0, 1 or 2
console.log(getRandomInt(1));
// Expected output: 0
console.log(Math.random());
// Expected output: a number from 0 to <1
๋ฌธ๋ฒ
Math.random()
๋งค๊ฐ๋ณ์
์์.
๋ฐํ ๊ฐ
0 ์ด์ 1 ๋ฏธ๋ง์ ๋ถ๋์์ซ์ ์์ฌ ๋์.
์์
JavaScript์ ์ซ์(number)๋ ๊ฐ๊น์ด ์ง์๋ก ๋ฐ์ฌ๋ฆผ๋๋(round-to-nearest-even behavior) IEEE 754 ๋ถ๋ ์์์ ์ซ์์ด๋ฏ๋ก, ์๋ ํจ์(Math.random()
์์ฒด์ ๋ฒ์ ์ ์ธ)์ ๋ํด ๋ช
์๋ ๋ฒ์๋ ์ ํํ์ง ์์ต๋๋ค. ๋งค์ฐ ํฐ ๋ฒ์๋ฅผ ์ ํํ๋ฉด ๊ทนํ ๋๋ฌผ๊ฒ ์ผ๋ฐ์ ์ผ๋ก ์ ์ธ๋๋ ์ต๋๊ฐ์ ๋๋ฌํ ์ ์์ต๋๋ค.
0 ์ด์ 1 ๋ฏธ๋ง์ ๋์ ์์ฑํ๊ธฐ
function getRandom() {
return Math.random();
}
๋ ๊ฐ ์ฌ์ด์ ๋์ ์์ฑํ๊ธฐ
์ด ์์ ๋ ์ง์ ๋ ๊ฐ ์ฌ์ด์ ์์์ ์ ์๋ฅผ ๋ฐํํฉ๋๋ค. ์ด ๊ฐ์ min
(๋๋ min
์ด ์ ์๊ฐ ์๋ ๊ฒฝ์ฐ min
๋ณด๋ค ํฐ ๋ค์ ์ ์) ๋ณด๋ค ์๊ณ max
๋ณด๋ค ์์ง๋ง ๊ฐ์ง ์์ ๊ฐ์
๋๋ค.
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
๋ ๊ฐ ์ฌ์ด์ ์ ์ ๋์ ์์ฑํ๊ธฐ
์ด ์์ ๋ ์ฃผ์ด์ง ๋ ๊ฐ ์ฌ์ด์ ์ ์์ธ ๋์๋ฅผ ์์ฑํฉ๋๋ค. ๋ฐํ๊ฐ์ min
(๋จ, min
์ด ์ ์๊ฐ ์๋๋ฉด min
๋ณด๋ค ํฐ ์ต์์ ์ ์)๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์ผ๋ฉฐ, max
๋ณด๋ค ์์ต๋๋ค.
function getRandomInt(min, max) {
const minCeiled = Math.ceil(min);
const maxFloored = Math.floor(max);
return Math.floor(Math.random() * (maxFloored - minCeiled) + minCeiled); // ์ต๋๊ฐ์ ์ ์ธ, ์ต์๊ฐ์ ํฌํจ
}
์ฐธ๊ณ :
์ด ์์ ์์ Math.round()
๋ฅผ ์ฌ์ฉํ๊ณ ์ถ์ ์ ์์ง๋ง, ์ด๋ ๊ฒ ํ๋ฉด ๋์๊ฐ ๊ณ ๋ฅด๊ฒ ๋ถํฌํ์ง ์๊ฒ ๋๋ฏ๋ก ํ์์ ๋ง์ง ์์ ์ ์์ต๋๋ค.
๋ ์๋ฅผ ํฌํจํ๋ ๋ ์ ์ฌ์ด์ ์ ์ ๋์ ์์ฑํ๊ธฐ
์์ getRandomInt()
ํจ์๋ ์ต์๊ฐ์ ํฌํจํ์ง๋ง, ์ต๋๊ฐ์ ํฌํจํ์ง ์์ต๋๋ค. ์ต์๊ฐ๊ณผ ์ต๋๊ฐ์ ๋ชจ๋ ํฌํจํ๋ ๊ฒฐ๊ณผ๊ฐ ํ์ํ ๊ฒฝ์ฐ, ์๋์ getRandomIntInclusive()
ํจ์๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค.
function getRandomIntInclusive(min, max) {
const minCeiled = Math.ceil(min);
const maxFloored = Math.floor(max);
return Math.floor(Math.random() * (maxFloored - minCeiled + 1) + minCeiled); // ์ต๋๊ฐ๋ ํฌํจ, ์ต์๊ฐ๋ ํฌํจ
}
๋ช ์ธ์
Specification |
---|
ECMAScriptยฎ 2026 Language Specification # sec-math.random |
๋ธ๋ผ์ฐ์ ํธํ์ฑ
Loadingโฆ