ใน JavaScript มี 2 วิธีเพิ่ม property ให้ object:
- Dot notation:
object.thingToAdd - Bracket notation:
object['thingToAdd']
Dot Notation
ลองดู dot notation ก่อน:
let dog = {
name: "Naya",
age: "2",
color: "black",
};
// Add item to dog object
dog.breed = "Rottweiler mix";
// Log object to console
console.log(dog);
// { name: "Naya", age: "2", color: "black", breed: "Rottweiler mix" }
Bracket Notation
Bracket notation มีข้อจำกัดน้อยกว่า ลองกับ dog object เดียวกัน:
let dog = {
name: "Naya",
age: "2",
color: "black",
};
dog["weight"] = "34kg";
console.log(dog);
// { name: "Naya", age: "2", color: "black", weight: "34kg" }
ในตัวอย่างนี้ ทำงานเหมือน dot notation
Dot Notation vs Bracket Notation
ลองเพิ่ม property ที่เป็น ตัวเลข ด้วย dot notation:
// Dot notation
dog.1 = "Property 1";
console.log(dog); // Uncaught SyntaxError: Unexpected number
Error! เพราะ dot notation ไม่สามารถใช้ตัวเลข ในชื่อ property ได้
แต่ bracket notation ใช้ได้ ตราบใดที่ identifier เป็น string:
// Bracket notation
dog["1"] = "Property 1";
console.log(dog);
// { 1: "Property 1", age: "2", color: "black", name: "Naya" }
ควรใช้แบบไหน?
Best practice: ใช้ dot notation เมื่อทำได้ เพราะอ่านง่ายกว่า แต่ถ้าต้องเพิ่ม property ที่ขึ้นต้นด้วยตัวเลข, สัญลักษณ์พิเศษ, หรือ reserved keyword ให้ใช้ bracket notation
Dot Notation:
- Property identifiers ใช้ได้แค่ alphanumeric (a-z), underscore (
_), หรือ$ - Property identifiers ห้าม เริ่มต้นด้วยตัวเลข
- Property identifiers ห้าม มี variables
Bracket Notation:
- Property identifiers ต้องเป็น string value type หรือ variable ที่ อ้างอิง string
- ใช้ช่องว่างใน identifiers ได้
[" property"] - String identifiers สามารถ เริ่มต้นด้วยตัวเลขได้
["1st"]