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

วิธีหาค่าสัมบูรณ์ (Absolute Value) ของตัวเลขใน JavaScript

ใช้ฟังก์ชัน Math.abs() หาค่าสัมบูรณ์ของตัวเลข คืนค่าสัมบูรณ์เสมอ

พารามิเตอร์

  • x – ตัวเลข (number)

ตัวอย่าง

<html>
  <head>
    <title>JavaScript Math abs() Method</title>
  </head>
  <body>
    <script>
      var value = Math.abs(-10);
      document.write("First Test Value: " + value); // 10
      document.write("<br />");
      var value = Math.abs(null);
      document.write("Second Test Value: " + value); // 0 (null -> 0)
      document.write("<br />");
      var value = Math.abs(20);
      document.write("Third Test Value: " + value); // 20
    </script>
  </body>
</html>

พฤติกรรมกับค่าต่างๆ

การประยุกต์ใช้

// ระยะห่างระหว่าง 2 จำนวน
function distance(a, b) {
  return Math.abs(a - b);
}

console.log(distance(10, 5));   // 5
console.log(distance(5, 10));   // 5
console.log(distance(-3, 7));   // 10
InputOutputหมายเหตุ
Math.abs(-10)10ติดลบ → บวก
Math.abs(10)10บวก → คงเดิม
Math.abs(0)0-
Math.abs(null)0null → 0
Math.abs("10")10string ตัวเลข → แปลงอัตโนมัติ
Math.abs("abc")NaNstring ไม่ใช่ตัวเลข → NaN
Math.abs(undefined)NaN-
Math.abs()NaNไม่มี argument → NaN