[REAL Deep Dive into JS] 29. Math

young_palleteΒ·2022λ…„ 10μ›” 2일
0

REAL JavaScript Deep Dive

λͺ©λ‘ 보기
29/46

🚦 본둠

정말 많이 μ“°λŠ” 빌트인 κ°μ²΄μž…λ‹ˆλ‹€.
Number νƒ€μž…μ˜ 값을 ꡬ할 λ•Œ 많이 μ‚¬μš©ν•˜λŠ” ν”„λ‘œνΌν‹°μ™€ λ©”μ„œλ“œλ“€μ΄ λ‚΄μž₯λ˜μ–΄ μžˆμŠ΅λ‹ˆλ‹€.

Math.PI

음... μ΄κ±°λŠ” 가끔, μ• λ‹ˆλ©”μ΄μ…˜ κ΅¬ν˜„ν•  λ•Œ 자주 μ‚¬μš©ν–ˆμŠ΅λ‹ˆλ‹€.
이 ν”„λ‘œνΌν‹°λ₯Ό κ°–κ³  μΊ”λ²„μŠ€μ— 원을 그릴 λ•Œ νŽΈν•˜λ”λΌκ΅¬μš”!

MDN에 μžˆλŠ” 예제λ₯Ό κ°€μ Έμ™€λ΄€μŠ΅λ‹ˆλ‹€.

function draw() {
  const canvas = document.getElementById("canvas");
  if (canvas.getContext) {
    const ctx = canvas.getContext("2d");

    ctx.beginPath();
    ctx.arc(75, 75, 50, 0, Math.PI * 2, true); // Outer circle
    ctx.moveTo(110, 75);
    ctx.arc(75, 75, 35, 0, Math.PI, false); // Mouth (clockwise)
    ctx.moveTo(65, 65);
    ctx.arc(60, 65, 5, 0, Math.PI * 2, true); // Left eye
    ctx.moveTo(95, 65);
    ctx.arc(90, 65, 5, 0, Math.PI * 2, true); // Right eye
    ctx.stroke();
  }
}

Math.abs

μ ˆλŒ€κ°’μ„ κ΅¬ν•˜λŠ” 데 μ‚¬μš©ν•©λ‹ˆλ‹€.

Math.round

μ΄λ²ˆμ— μ‚¬μš©ν•  일이 μžˆμ—ˆλŠ”λ°μš”. μ „λ‹¬λœ 숫자의 μ†Œμˆ˜μ  μ΄ν•˜λ₯Ό λ°˜μ˜¬λ¦Όν•©λ‹ˆλ‹€.
κ·Έλ ‡μ§€λ§Œ, μ΄λŸ¬ν•œ λ©”μ„œλ“œλŠ” μ‹€μ œλ‘œ μ™„μ „νžˆ μ†Œμˆ˜μ μ„ 잘 μ²˜λ¦¬ν•˜μ§€ λͺ»ν•©λ‹ˆλ‹€. μ΄μœ λŠ” λΆ€λ™μ†Œμˆ˜μ  λ•Œλ¬ΈμΈλ°μš”!

λ”°λΌμ„œ, 이 λΈ”λ‘œκ·Έμ— λ”°λ₯΄λ©΄, μœ„ λ©”μ„œλ“œλ₯Ό μ’€ 더 κ°€κ³΅ν•΄μ„œ μ‚¬μš©ν•΄μ•Ό λͺ¨λ“  μΌ€μ΄μŠ€λ₯Ό μ²˜λ¦¬ν•  수 μžˆλ‹€κ³  ν•©λ‹ˆλ‹€.

function roundTo(num, pointPlace) {
    return +(Math.round(num + `e+${pointPlace}`)  + `e-${pointPlace}`);
}

Math.ceil, Math.floor

올림과 내림에 κ΄€ν•œ λ©”μ„œλ“œμž…λ‹ˆλ‹€.

Math.sqrt

인수둜 μ „λ‹¬λœ κ°’μ˜ μ œκ³±κ·Όμ„ λ°˜ν™˜ν•©λ‹ˆλ‹€.

Math.random

0 <= value < 1의 값을 λ°˜ν™˜ν•©λ‹ˆλ‹€.
μ€‘μš”ν•œ ν¬μΈνŠΈλŠ”, 1을 λ°˜ν™˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

Math.pow(λ°‘, μ§€μˆ˜)

첫번째 인자λ₯Ό μ§€μˆ˜λ§ŒνΌ κ±°λ“­μ œκ³±ν•œ 값을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

Math.min, Math.max

μ΅œμ†Ÿκ°’κ³Ό μ΅œλŒ“κ°’μ„ λ°˜ν™˜ν•©λ‹ˆλ‹€.

πŸŽ‰ 마치며

음... μ‰¬μ–΄κ°€λŠ” 파트라고 보면 될 것 κ°™λ„€μš”.
μ€‘μš”ν•˜μ§€ μ•Šμ€ 건 μ•„λ‹ˆμ§€λ§Œ, κ·Έλ ‡λ‹€κ³  μ—„μ²­ μ—λ„ˆμ§€λ₯Ό μŸμ„ νŒŒνŠΈλŠ” μ•„λ‹Œ 것 κ°™μŠ΅λ‹ˆλ‹€.
μ‹€μ œλ‘œ μ €μžλ„, Math.sin λ“± λ‹€μ–‘ν•œ λ©”μ„œλ“œκ°€ 아직 λ§ŽμŒμ—λ„ ν•΅μ‹¬λ§Œ μ„œμˆ ν•œ 것 κ°™μŠ΅λ‹ˆλ‹€.

λ‹€λ§Œ, μ € μ—­μ‹œ μ΄λ²ˆμ— round ν•¨μˆ˜μ˜ 경우 뢀동 μ†Œμˆ˜μ  μ΄μŠˆκ°€ μžˆμ–΄μ„œ, 정말 μƒˆλ‘œμ› λ˜ 기얡이 μžˆμ–΄μš”.

μš”μƒˆ λŠλΌλŠ” 건, μž˜ν•˜λŠ” κ°œλ°œμžλž€... 엣지 μΌ€μ΄μŠ€κΉŒμ§€ 잘 νŒŒμ•…ν•΄μ„œ, μ•ˆμ •μ μœΌλ‘œ ν”„λ‘œκ·Έλž˜λ°ν•  수 μžˆλ„λ‘ μ§€μ›ν•˜λŠ” κ°œλ°œμžκ°€ μ•„λ‹κΉŒ μƒκ°ν•˜λ„€μš”.

그럼, λ‹€λ“€ 멋진 κ°œλ°œμžκ°€ λ˜μ‹œκΈΈ 바라며. 이상!

profile
People are scared of falling to the bottom but born from there. What they've lost is nth. πŸ˜‰

0개의 λŒ“κΈ€