2011-11-01 87 views
-4

我想在下面聲明的數組img中獲取第一個文件名(Apple_Desk_1920 x 1200 widescreen.jpg)。我該怎麼做呢?如何獲取javascript數組中的第一個值

這是我的代碼:

var img = [{ 
       "image" : "Apple_Desk_1920 x 1200 widescreen.jpg" 
       }, { 
       "image" : "aa.jpg" 
       }, { 
       "image" : "auroracu4.jpg" 
       }, { 
       "image" : "blue-eyes-wallpapers_22314_1920x1200.jpg" 
       }, { 
       "image" : "blue-lights-wallpapers_22286_1920x1200.jpg" 
       }, { 
       "image" : "fuchsia-wallpapers_17143_1920x1200.jpg" 
       }, { 
       "image" : "leaves.jpg" 
       }, ]; 
+4

如何閱讀一些文檔['>'陣列(https://developer.mozilla.org/en/JavaScript/Guide/Predefined_Core_Objects#Referring_to_Array_Elements)和['>'對象] (https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects#Objects_and_Properties)?這就是文檔和教程的用途。 –

回答

3
// dot notation 
console.log(img[0].image); 

或:

// square-bracket notation 
console.log(img[0]['image']); 

會得到它給你,因爲你有對象的數組。

4

它是:

var variableName = img[0].image; 

你有什麼有對象的數組。要獲得數組條目,請使用帶數組索引的[]0比數組的length小1)。在這種情況下,這給你一個對象的引用。要訪問對象的屬性,可以使用文字符號,如上所述(obj.image),或使用帶有字符串屬性名稱(obj["image"])的[]。他們做的事情完全一樣。 (實際上,用於訪問對象屬性的[]表示法是將數據「索引」到數組中時所使用的; JavaScript數組aren't really arrays,它們只是具有幾個特殊功能的對象。)

因此,打破線之上向下:

var variableName =    // Just so I had somewhere to put it 
        img[0]  // Get the first entry from the array 
          .image; // Get the "image" property from it 
相關問題