๐ค Number ํํค์น๊ธฐ
๋ช ๊ฐ์ง ์ํ ๊ด๋ จ ๋ฉ์๋๋ฅผ ๋ณด๋ ค๊ณ ํฉ๋๋ค.
์ํ ๊ณ์ฐ์ ์ํด์๋ JavaScript์์ ์ ๊ณตํ๋ Math ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํฉ๋๋ค.
JavaScript Math Object๐ฆด ๋ฐ์ฌ๋ฆผ ํจ์
console.log(Math.round(2.5)); //3 console.log(Math.round(2.49)); //2 console.log(Math.round(2)); //2 console.log(Math.round(2.82)); //3
๐ฆด ์ฌ๋ฆผ ํจ์
console.log(Math.ceil(2.5)); //3 console.log(Math.ceil(2.49)); //3 console.log(Math.ceil(2)); //2 console.log(Math.ceil(2.82)); //3
๐ฆด ๋ด๋ฆผํจ์๋ floor
console.log(Math.floor(2.5)); //2 console.log(Math.floor(2.49)); //2 console.log(Math.floor(2)); //2 console.log(Math.floor(2.82)); //2
๐ฆด ๋๋คํจ์
var randomNumber = Math.random(); console.log(randomNumber); //0.9495925277638846
var randomNumber = Math.random(); console.log(Math.floor(randomNumber*10)); //1
randomNumber*10 ์ ๊ฐ์ 1์ ์๋ฆฌ์์ ์์ฒญ ๊ธด ์์์๋ฆฌ๋ก ์ด๋ฃจ์ด์ ธ ์๋ค.
ex) 9.697009826327621
์ด๋ ๊ฒ ๊ตฌํ ํ, ์์์๋ฆฌ๋ ๋ค ๋ฒ๋ฆฌ๋๋ก ๋ด๋ฆผํจ์๋ฅผ ์ฌ์ฉํ์ฌ 0~10 ์ฌ์ด์ ๋๋ค์๋ฅผ ๊ตฌํ ์ ์๋ค.
๐ฆด Assignment
์์ผ๋ก ๋๋คํจ์๋ฅผ ์ธ ์ผ์ด ์ ๋ง ๋ง์ต๋๋ค.
๊ทธ๋ฐ๋ฐ Math.random()์ผ๋ก๋ ๋ด๊ฐ ์ํ๋ ๋ฒ์์ ๋๋ค์๋ฅผ ์ป์ ์๊ฐ ์์ต๋๋ค.
ํญ์ 0.0000000000000000์์ 0.9999999999999999 ์ฌ์ด ๊ฐ์์๋ง returnํด์ฃผ๊ธฐ ๋๋ฌธ์ด์ฃ .
์ต์(min), ์ต๋๊ฐ(max)์ ๋ฐ์ ๊ทธ ์ฌ์ด์ ๋๋ค์๋ฅผ returnํ๋ ํจ์๋ฅผ ๊ตฌํํด์ฃผ์ธ์.
- ํจ์๋ ์งง์ง๋ง, ์ด๋ฒ์๋ ์ํ์ ๋๋ฅผ ์กฐ๊ธ ์จ์ผ ํ๋ assignment์ ๋๋ค.
function getRandomNumber(min, max) { return Math.floor((Math.random() * (max - min + 1)) + min); }