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

โอเปอเรเตอร์ลบ (-) ใน JavaScript คืออะไร?


โอเปอเรเตอร์ลบ (-) ใช้ ลบ operand ขวามือออกจาก operand ซ้ายมือ (Left - Right) เป็น Binary Operator (รับ 2 operand)

ตัวอย่างโค้ด

<html>
<body>
  <script>
    var a = 40;
    var b = 25;
    document.write("a - b = ");
    result = a - b;
    document.write(result); // 15
  </script>
</body>
</html>

พฤติกรรมกับชนิดข้อมูล (Type Coercion)

ไม่เหมือน + ที่ต่อสตริง - จะ พยายามแปลง operand ทั้งสองเป็นตัวเลขเสมอ:

Operand 1Operand 2ผลลัพธ์คำอธิบาย
1055ตัวเลขปกติ
"10"55String → Number
10"5"5String → Number
"10""5"5ทั้งคู่ String → Number
truefalse1true=1, false=0
null5-5null=0
undefined5NaNundefined=NaN
"abc"5NaN"abc" ไม่แปลงเป็นตัวเลขได้

Unary Negation (-) vs Binary Subtraction (-)

สัญลักษณ์ - มี 2 หน้าที่:

Unary Negation Example

var x = 10;
var y = -x;    // -10
var z = -(-5); // 5
var n = -"10"; // -10 (แปลง String -> Number แล้ว Negate)

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

  • คำนวณความแตกต่าง: diff = a - b
  • กลับเครื่องหมาย: x = -x
  • Date Diff: days = (date2 - date1) / (1000*60*60*24)
  • แปลง String เป็น Number: num = +"123" (Unary +) หรือ num = "123" - 0

ข้อควรระวัง

  • NaN แพร่กระจาย: NaN - 5 = NaN, 5 - NaN = NaN
  • Precision Issue: 0.3 - 0.1 = 0.19999999999999998 (ใช้ Math.round หรือ Library)
  • Overflow: จำนวนใหญ่เกิน Number.MAX_SAFE_INTEGER อาจไม่แม่นยำ
ประเภทชื่อตัวอย่างผลลัพธ์
UnaryNegation-5, -xกลายเป็นลบ / บวก
BinarySubtraction10 - 3ลบ