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

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


โอเปอเรเตอร์ Unary Negation (-) ใช้ แปลง operand เป็นตัวเลข แล้วกลับเครื่องหมาย (บวก→ลบ, ลบ→บวก) ต่างจาก Binary Subtraction ที่ลบตัวเลขสองตัว

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

<html>
<body>
  <script>
    var a = true;
    var b = '0xFF';
    var c = "false";
    var d, e, f;
    
    d = -a;  // -true → -1
    e = -b;  // -'0xFF' → -255
    f = -c;  // -"false" → NaN
    
    document.write("-true = " + d + "<br />");
    document.write("-'0xFF' = " + e + "<br />");
    document.write("-false = " + f);
  </script>
</body>
</html>

กระบวนการทำงาน

  1. แปลง Operand เป็น Number (ToNumber Abstract Operation)
  2. กลับเครื่องหมาย (Negate)

ตารางการแปลง (ToNumber)

InputToNumberNegated
true1-1
false0-0 (แสดงเป็น 0)
"123"123-123
"0xFF"255-255
"" (empty)0-0
"abc"NaNNaN
null0-0
undefinedNaNNaN
[5]5-5
[1,2]NaNNaN
{}NaNNaN

การใช้งานทั่วไป

1. กลับเครื่องหมายตัวเลข

var x = 10;
var y = -x; // -10
var z = -y; // 10

2. แปลง String เป็น Number (Quick Convert)

-"-123"   // 123 (Double Negative)
+"123"     // 123 (Unary Plus - แนะนำมากกว่า)
"123" - 0  // 123

3. คำนวณความต่างสัมพันธ์

function diff(a, b) {
  return a > b ? a - b : -(b - a); // หรือ Math.abs(a - b)
}

Unary Plus (+) vs Unary Negation (-)

โอเปอเรเตอร์ชื่อฟังก์ชันตัวอย่าง
+xUnary Plusแปลงเป็น Number (ไม่กลับเครื่องหมาย)+"123" = 123
-xUnary Negationแปลงเป็น Number แล้วกลับเครื่องหมาย-"123" = -123

ข้อควรระวัง

  • Precedence สูงกว่า Binary Operators: -a + b = (-a) + b
  • --x คือ Decrement Operator ไม่ใช่ Double Negation (ใช้ - -x แทน)
  • ผลลัพธ์เป็น NaN หากแปลงไม่ได้ → การคำนวณต่อจะได้ NaN ตลอด