先定義一個物件作為示例:
var fish = {
head : 1,
tail : 1,
feature : {
speak : false,
swim : true
}
}
其一,點運算子:
console.log(fish.head); // 1
console.log(fish.tail); // 1
console.log(fish.feature); // Object { head:1, tail:1, feature: Object }
其二,[] 運算子:
console.log(fish['head']); // 1
這裡要注意:中括號內的屬性名必須是字串形式,例如:
console.log(fish[head]); // 錯誤!head 未定義
那麼以下代碼是否正確呢?
for (var prop in fish) {
console.log(fish[prop]);
}
答案是肯定的。因為遍歷物件屬性時,prop 是以字串型別存在的,依次為 'head'、'tail'、'feature',所以用中括號搭配變數 prop 剛好能正確取到對應屬性值。