Programming Track
JavaScript
Operators
Assignment Operators
เรียนรู้ตัวดำเนินการกำหนดค่าทั้ง = และ compound operators (+=, -=, *=, /=, %=) พร้อมฝึกอัปเดตยอดเงินและคะแนนผ่าน Lab จริง
Assignment Operator คืออะไร
Assignment Operator ใช้กำหนดค่าให้ตัวแปร ตัวพื้นฐานคือ = ซึ่งเก็บค่าทางขวาไว้ในตัวแปรทางซ้าย นอกจากนี้ยังมี compound assignment operators เช่น += ที่รวมการคำนวณและกำหนดค่าในขั้นตอนเดียว
| Operator | เทียบเท่ากับ | ตัวอย่าง (x = 10) | ผลลัพธ์ |
|---|---|---|---|
| = | กำหนดค่า | x = 10 | x = 10 |
| += | x = x + n | x += 5 | x = 15 |
| -= | x = x - n | x -= 3 | x = 7 |
| *= | x = x * n | x *= 2 | x = 20 |
| /= | x = x / n | x /= 4 | x = 2.5 |
| %= | x = x % n | x %= 3 | x = 1 |
| **= | x = x ** n | x **= 2 | x = 100 |
ตัวอย่างการใช้งานจริง — อัปเดตยอดเงินในบัญชี
Compound assignment — อัปเดตยอดเงินJS
ใช้ += และ -= แทนการเขียน balance = balance + amount ทุกครั้ง
let balance = 1000;
balance += 500; // ฝาก: balance = 1500
balance -= 200; // ถอน: balance = 1300
balance *= 1.02; // ดอกเบี้ย 2%: balance = 1326
balance -= 50; // ค่าธรรมเนียม: balance = 1276
console.log("ยอดเงินคงเหลือ:", balance); // 1276ตัวอย่าง — นับคะแนนในเกม
ใช้ += สำหรับ score counterJS
let score = 0;
score += 10; // เก็บเหรียญ: 10
score += 25; // ฆ่าศัตรู: 35
score += 100; // ผ่านด่าน: 135
score -= 20; // โดนโจมตี: 115
console.log("คะแนน:", score); // 115สรุป
- = กำหนดค่าพื้นฐาน
- +=, -=, *=, /= ย่อการเขียน x = x + n ให้สั้นลง
- ใช้ compound assignment เมื่อต้องอัปเดตค่าตัวแปรซ้ำๆ เช่น score, balance, count
- %=, **= ใช้น้อยกว่าแต่มีประโยชน์เมื่อต้องการ