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

Exponentiation Operator (**) ใน JavaScript

ใช้ Exponentiation operator หาตัวเลขยกกำลัง อีกตัวหนึ่ง สัญลักษณ์ ** มี Math.pow() แล้วแต่ ** เป็นมาตรฐานหลายภาษา (Python, Ruby ฯลฯ)

ข้อจำกัด

Negative bases ต้องอยู่ใน parentheses มิฉะนั้นจะ error

ตัวอย่างที่ 1 (Positive Base)

<html> <body> 
    <script> 
        var res1 = Math.pow(3, 2); 
        var res2 = (3) ** 2; 
        document.write(res1); 
        document.write("<br>"); 
        document.write(res2); 
    </script> 
</body> </html>

ผลลัพธ์

9 9

ตัวอย่างที่ 2 (Negative Base)

Math.pow() ไม่มีปัญหา แต่ ** ต้องมี parentheses ครอบ negative base

<html> <body> 
    <script> 
        var res1 = Math.pow(-3, 2); 
        var res2 = (-3) ** 2; // ถ้าไม่มี parentheses จะ error 
        document.write(res1); 
        document.write("<br>"); 
        document.write(res2); 
    </script> 
</body> </html>

ผลลัพธ์

9 9