Unary Plus Operator: แปลงสตริงเป็นตัวเลข
เครื่องหมาย + นำหน้าตัวแปร (Unary Plus) จะแปลงค่าให้เป็น Number type
ตัวอย่างโค้ด
var firstValue = "1000";
console.log("ชนิดของ firstValue = " + typeof firstValue); // string
var secondValue = 1000;
console.log("ชนิดของ secondValue = " + typeof secondValue); // number
// ใช้ unary plus แปลงสตริงเป็นตัวเลข
console.log("ชนิดของ +firstValue = " + typeof +firstValue); // number
var output = +firstValue + secondValue;
console.log("ผลบวก = " + output); // 2000
วิธีรัน
node fileName.js
ผลลัพธ์
ชนิดของ firstValue = string
ชนิดของ secondValue = number
ชนิดของ +firstValue = number
ผลบวก = 2000
คำอธิบาย
+ "1000"→1000(number)- เทียบเท่า
Number("1000")หรือparseFloat("1000")แต่สั้นกว่า - ถ้าแปลงไม่ได้ จะได้
NaN:+ "abc"→NaN - ใช้ได้กับ Boolean:
+true→1,+false→0 - ใช้ได้กับ Date:
+new Date()→ timestamp (มิลลิวินาที)
กรณีใช้งานทั่วไป
// รับค่าจาก input (string) แปลงคำนวณ
const price = +"100";
const qty = +"2";
console.log(price * qty); // 200