โอเปอเรเตอร์ 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>
กระบวนการทำงาน
- แปลง Operand เป็น Number (ToNumber Abstract Operation)
- กลับเครื่องหมาย (Negate)
ตารางการแปลง (ToNumber)
| Input | ToNumber | Negated |
true | 1 | -1 |
false | 0 | -0 (แสดงเป็น 0) |
"123" | 123 | -123 |
"0xFF" | 255 | -255 |
"" (empty) | 0 | -0 |
"abc" | NaN | NaN |
null | 0 | -0 |
undefined | NaN | NaN |
[5] | 5 | -5 |
[1,2] | NaN | NaN |
{} | NaN | NaN |
การใช้งานทั่วไป
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 (-)
| โอเปอเรเตอร์ | ชื่อ | ฟังก์ชัน | ตัวอย่าง |
+x | Unary Plus | แปลงเป็น Number (ไม่กลับเครื่องหมาย) | +"123" = 123 |
-x | Unary Negation | แปลงเป็น Number แล้วกลับเครื่องหมาย | -"123" = -123 |
ข้อควรระวัง
- Precedence สูงกว่า Binary Operators:
-a + b = (-a) + b
--x คือ Decrement Operator ไม่ใช่ Double Negation (ใช้ - -x แทน)
- ผลลัพธ์เป็น
NaN หากแปลงไม่ได้ → การคำนวณต่อจะได้ NaN ตลอด