2016-08-13 37 views
-1
car = { 
color: 'green', 
speed: '340', 
drive: function() { 
    alert("brrrrrrm"); 
} 
} 

這工作:爲什麼對象點符號不適合......工作在循環?

for(elem in car) { 
    console.log(car[elem]); 
} 

但是,這並不工作,對每一個元素返回undefined:

for(elem in car) { 
    console.log(car.elem); 
} 
+2

你有任何鍵名爲「ELEM」?不,那是爲什麼。 –

+1

@GerardoFurtado該死的,這是快速和準確的,謝謝! – user1089548

+0

[這個答案](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets)可能會給一些啓發。 – Tholle

回答

1

當你寫的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 
相關問題