Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เมธอด Math.pow() ใน JavaScript: ยกกำลัง

Math.pow()

คำนวณ baseexponent (Base ยกกำลัง Exponent) รองรับทุกชนิดตัวเลข

ไวยากรณ์

Math.pow(base, exponent)

ตัวอย่าง 1: จำนวนเต็มบวก

<script>
  document.write(Math.pow(9, 3)); // 729 (9³)
</script>

ตัวอย่าง 2: หารากที่ n (Fractional Exponent)

<script>
  document.write(Math.pow(27, 1/3)); // 3 (รากที่ 3 ของ 27)
  document.write(Math.pow(16, 0.5)); // 4 (รากที่ 2 ของ 16)
</script>

ตัวอย่าง 3: Base ติดลบ

<script>
  document.write(Math.pow(-9, 3));  // -729
  document.write(Math.pow(-9, 2));  // 81
  document.write(Math.pow(-9, 0.5)); // NaN (รากที่ 2 ของติดลบ)
</script>

Exponentiation Operator ** (ES2016)

แนะนำใช้ ** แทน เพราะอ่านง่ายกว่า และรองรับ BigInt

9 ** 3        // 729
27 ** (1/3)   // 3
-9 ** 3       // -729 (Note: -(9**3) ต้องเขียนเป็น (-9)**3 เพื่อได้ -729)
2n ** 10n     // 1024n (BigInt)

ข้อควรระวัง

  • Math.pow(-9, 0.5) = NaN (ไม่มี Real Root)
  • Precision Issue: Math.pow(0.1, 2) = 0.010000000000000002
  • BigInt ต้องใช้ ** ไม่รองรับ Math.pow()