μƒˆμ†Œμ‹

🍎/Javascript

[Javascript] λ‚œμˆ˜ μƒμ„±ν•˜κΈ° (λ²”μœ„ μ§€μ •, μ •μˆ˜ λ‚œμˆ˜ 생성)

  • -

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

 

Contents

ν¬μŠ€νŒ… μ£Όμ†Œ 볡사 μ™„λ£Œ! 🌈

이 글이 도움이 λ˜μ—ˆλ‹€λ©΄ 곡감❀️‍πŸ”₯뢀탁 λ“œλ €μš” (βˆ—β›βŒ„β›βˆ—)