2011-11-01 91 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 
相关问题