要從一個物件中獲取屬性的第一個方法是使用點符號(dot notation),另一種是使用括號(bracket notation)。
const andy = {
lastName: "Wu",
age: 25,
height: 177,
parents: ["Jay", "Chloe"]
};
console.log(andy);
// {lastName: "Wu", age: 25, height: 177, parents: Array(2)}
console.log(andy.age);
// 25
console.log(andy["age"]);
// 25
這兩種方法的差別在於,括號中不一定只能使用字串,我們可以加入任何我們想要的表達式,例如:
console.log(andy["last" + "Name"]);
// Wu
如果我們想要為這個物件添加屬性,我們一樣可以使用點符號或括號來達成:
const shoppingList = {
drinks: "milk",
fruits: ["apple", "cherry"],
dessert: "strawberry cake"
};
shoppingList.vege = "lettuce";
shoppingList["meat"] = "beef";
console.log(shoppingList);
// {drinks: "milk", fruits: Array(2), dessert: "strawberry cake", vege: "lettuce", meat: "beef"}