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

การใช้งานฟังก์ชัน Math.hypot() ใน JavaScript

Math.hypot()

Math.hypot() คำนวณรากที่สองของผลรวมกำลังสองของอาร์กิวเมนต์ที่ส่งเข้าไป ใช้หาความยาวด้านตรงข้ามมุมฉาก (hypotenuse) ของสามเหลี่ยมมุมฉาก

ไวยากรณ์

Math.hypot(arg1, arg2, ...);

ตัวอย่าง หาด้านตรงข้ามมุมฉาก

<html> <body> <script> 
    document.write(Math.hypot(7, 24)); 
    document.write("<br>"); 
    document.write(Math.hypot(7, "hi")); 
</script> </body> </html>

ผลลัพธ์

25 NaN

รองรับค่าลบ และอาร์กิวเมนต์มากกว่า 2 ตัว

ตัวอย่าง ค่าลบ

<html> <body> <script> 
    document.write(Math.hypot(-7, -24)); 
    document.write("<br>"); 
    document.write(Math.hypot(-3, -4)); 
</script> </body> </html>

ผลลัพธ์

25 5

ตัวอย่าง หลายอาร์กิวเมนต์

<html> <body> <script> 
    document.write(Math.hypot(1, 2, 3)); 
</script> </body> </html>

ผลลัพธ์

3.74165738677