2017-07-25 126 views
0

/*枚舉爲什麼我會得到不同的結果?使用name.property和name [property]

for in語句可以遍歷對象中的所有屬性名稱。枚舉將包含函數和原型屬性。 */

//第一個代碼我寫

var fruit = { 
    apple: 2, 
    orange: 5, 
    pear:1 
}, 
sentence = 'I have', 
quantity; 
for (kind in fruit) { 
    quantity = fruit[kind]; 
    sentence += quantity + '' + kind + 
       (quantity === 1?'': 's') + 
       ', '; 
} 
sentence = sentence.substr(0,sentence.length-2) + '.'; 
alert(sentence); 

//第二個代碼我寫

var fruit = { 
    apple: 2, 
    orange: 5, 
    pear:1 
}, 
sentence = 'I have', 
quantity;// 
for (kind in fruit) { 
    quantity = fruit.kind; 
    sentence += quantity + '' + kind + 
       (quantity === 1?'': 's') + 
       ', '; 
} 
sentence = sentence.substr(0,sentence.length-2) + '.'; 
alert(sentence); 
+0

因爲fruit.kind等於水果。['kind']。你的第二個例子中沒有評價類。 – Bellian

+0

語法錯誤:'fruit。['kind']'實際上應該是'fruit ['kind']' –

回答

0

那是因爲你kind是一個變量。

當你寫fruit.kind,JS引擎實際上將其解釋爲fruit['kind']

1

這個問題的根源是訪問屬性之間的點(obj.prop)對數組符號(差OBJ [丙])。

  • obj.prop手段訪問名爲屬性「託」這是從OBJ對象訪問。
  • OBJ [丙]另一方面裝置:確定所述變量的字符串值和訪問屬性匹配OBJ對象上的字符串值。

在第一種情況:

for (kind in fruit) { 
    quantity = fruit[kind]; 
} 

變量獲得分配字符串 「蘋果」, 「橙」, 「梨」 的for循環執行過程中。所以你可以像這樣的水果[「蘋果」](相當於fruit.apple),水果[「orange」](或fruit.orange)和水果[「pear」]或(fruit.pear )。

在第二種情況:

for (kind in fruit) { 
    quantity = fruit.kind; 
    ... 
} 

你總是訪問水果對象的那種財產。由於水果對象不具有屬性,您將永遠得到undefined

如果你想了解更多關於如何解決JavaScript中的財產訪問問題,你可以看看Secrets of the JavaScript Ninja本書 - 它幫助了我。

相關問題