在 JS 對象中,調用屬性一般有兩種方法——點和中括號的方法。
例如
- 使用點方法
var obj = {
name: "cedric"
}
console.log(obj.name); // cedric
- 使用 [ ] 方法
var obj = {
name: "cedric"
}
console.log(obj["name"]); // cedric
點方法是在對象名后面跟上屬性名,而中括號方法里的索引存放的與屬性名字相同的字符串 。
二者區別
- 點方法后面跟的必須是一個指定的屬性名稱,而中括號方法里面可以是變量。例如
var haha = "name";
console.log(obj.haha); // undefined
console.log(obj[haha]); // cedric
- 中括號方法里面的屬性名可以是數字,而點方法后面的屬性名不可以是數字
當動態為對象添加屬性時,必須使用 中括號 [], 不可以用點方法