當你寫的car.elem
,你要訪問的elem
財產汽車對象,它不存在。
但是當你使用car[elem]
,你試圖訪問其名稱一樣存儲在變量ELEM車對象的屬性。
因此,如果您使用「點號」,你會最終調用車對象的ELEM財產。
car = {
color: 'green',
speed: '340',
elem: 'This is the elem property of car object',
drive: function() {
alert("brrrrrrm");
}
}
訪問屬性:
for(elem in car) {
console.log(car[elem]);
}
控制檯輸出:
green
340
This is the elem property of car object
function() {
alert("brrrrrrm");
}
然後我們這樣做:
for(elem in car) {
console.log(car.elem);
}
控制檯輸出:
This is the elem property of car object
This is the elem property of car object
This is the elem property of car object
This is the elem property of car object
你有任何鍵名爲「ELEM」?不,那是爲什麼。 –
@GerardoFurtado該死的,這是快速和準確的,謝謝! – user1089548
[這個答案](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets)可能會給一些啓發。 – Tholle