Operator JavaScript += บวก 2 ค่าแล้ว assign ผลลัพธ์ให้ variable เรียกว่า addition assignment operator สะดวกกว่า variable = X + Y แบบเดิม
Plus sign และ equals sign ติดกัน? ใน JS มีความหมายเฉพาะ: addition assignment operator
JavaScript += Operator คืออะไร?
+= บวกค่าข้างขวาให้ variable ข้างซ้าย แล้ว assign ผลลัพธ์กลับให้ variable ข้างซ้าย
Syntax:
let welcome = "Hello there, "; console.log(welcome += "Sophie."); // "Hello there, Sophie."
Variable "welcome" = "Hello there, " ใช้ += บวก "Sophie." ผลลัพธ์ assign กลับ welcome
2 การใช้งาน: 1) บวกตัวเลข 2) รวม strings
Operator นี้เทียบเท่า:
x = x + y
แต่ += อ่านง่ายกว่า มักใช้ใน loops กับ counter นับรอบ
ตัวอย่าง: บวกตัวเลข (นับรอบ Loop)
นับว่า "The Count of Monte Cristo" ปรากฏกี่ครั้งใน array:
var books = [
"The Count of Monte Cristo",
"All My Sons",
"Of Mice and Men",
"The Count of Monte Cristo",
"To Have and Have Not"
];
var count = 0;
for (b in books) {
if (books[b] === "The Count of Monte Cristo") {
count += 1; // increment counter
}
}
console.log(`The Count of Monte Cristo was voted Book of the Year ${count} times.`);
// Output: 2 times
ตัวอย่าง: รวม Strings
รวม strings ได้ง่ายกว่า variable = x + y
หาเค้กที่ขึ้นต้นด้วย "B" ใน list รวมเป็น string:
var cakes = ["Babka", "Raspberry Ganache", "Strawberry Cheesecake", "Baked Alaska"];
var start_with_b = "| ";
for (cake in cakes) {
if (cakes[cake].startsWith("B")) {
var message = cakes[cake] + " | ";
start_with_b += message; // append เข้า string
}
}
console.log(start_with_b); // "| Babka | Baked Alaska | "
ใช้ startsWith() เช็คขึ้นต้น "B" สร้าง message แล้ว += append เข้า start_with_b
ทางเลือกอื่น: concatenation operator (+) หรือ concat() method
สรุป
Addition assignment (+=) operator บวกค่าแล้ว assign ให้ variable ใช้บ่อยกับ: เพิ่มค่าต่อท้าย string หรือ บวกตัวเลข (counter ใน loops)