2015-01-17 94 views
-1

我無法加入我的空數組成可經由托架符號方法我的對象。我知道如何讓我的空數組通過點符號的對象,但我就是不明白,爲什麼括號表示法是不是爲我工作。如何將一個空數組添加到對象?

更新:我現在明白我的問題;點符號&括號標記之間的上下文切換矇蔽我&我完全沒有記得,我在第3塊 - 動物[聲音](忘了「」)試圖訪問該屬性噪聲的屬性值,這我沒有在我的對象尚未創建

創建&屬性添加到我的對象

var animal = {}; 
animal.username = "Peggy"; 
animal["tagline"] = "Hello"; 

那麼,這將創造這樣的:

animal { 
     tagline: "Hello", 
     username: "Peggy" 
} 

爲什麼不會以下工作當我試圖將它添加到我的對象?

var noises = []; 
animal[noises]; 

我在我的控制檯得到這個(同上):

animal { 
     tagline: "Hello", 
     username: "Peggy" 
} 

我能得到我的結果是這樣的:

animal.noises = []; 

它輸出到我這控制檯:

animal { 
    noises: [], 
    tagline: "Hello", 
    username: "Peggy" 
} 

但那仍然是leav問我這個問題:爲什麼不通過括號表示法工作?

+1

'動物[噪聲];'意味着您正嘗試使用由'噪聲'給出的名稱來訪問'動物'的屬性。你沒有在那裏創建任何屬性。 – thefourtheye

+0

我剛更新了這個問題。看看第三個代碼塊 –

+0

@ CliffordFajardo,它不會改變任何東西。你沒有料到'animal [「Hello」];'創建一個名爲'tagline'的屬性值爲'Hello',是嗎?現在你爲什麼會期望'animal [[]]'(實際上是你的嘗試)應該創建一個名爲'noises'的屬性?你顯然不知道括號表示法的含義,你應該在初學者的JavaScript教程中查看它。 –

回答

2

使用

animal.noises = noises; 

animal['noises'] = noises; 

當您使用animal[noises];當你試圖從對象中讀取數據的意思。

+0

謝謝。我也沒有記得,用括號表示我需要「」在周圍的噪音。你的迴應簡潔明瞭。 –

1

對於animal[noises]

  • animal是對象
  • noises是對象animal

的鍵/屬性以及陣列不能是鍵。如果你想要把noises數組中animal對象,你可以做如下,

animal['noises'] = noises; 
1

你的情況,你必須嘗試

animal['noises']=noises 

陣列[]符號用於獲取對象的屬性,需要一個關於它的報價。數組符號通常用於獲取包含特殊字符的對象的標識符。說,

var animal={ 
     "@tiger":'carnivore' // you can't have @tiger without quote as identifier 
    } 
    console.log([email protected]) // it will give ERROR 
    console.log(animal['@tiger']) // it will print out 'carnivore' 

this link has good explanation on array and dot notation

+0

謝謝你的偉大,簡潔的例子! –