如何获取javascript数组中的第一个值
我想获得下面声明的数组如何获取javascript数组中的第一个值,javascript,arrays,Javascript,Arrays,我想获得下面声明的数组img中的第一个文件名(Apple\u Desk\u 1920 x 1200 widescreen.jpg)。我该怎么做 这是我的代码: var img = [{ "image" : "Apple_Desk_1920 x 1200 widescreen.jpg" }, { "image" : "aa.jpg" }, {
img
中的第一个文件名(Apple\u Desk\u 1920 x 1200 widescreen.jpg
)。我该怎么做
这是我的代码:
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"
}, ];
或:
将为您获取它,因为您有一个对象数组。它是:
var variableName = img[0].image;
这里有一个对象数组。要获取数组项,请使用带有数组索引的[]
(0
到小于数组长度的一个)。在本例中,这将为您提供对对象的引用。要访问对象的属性,可以使用我上面提到的文字符号(obj.image
),或者使用带有字符串属性名称的[]
(obj[“image”]
)。他们做完全相同的事情。(事实上,访问对象属性的[]
符号是您在“索引”到数组中时使用的;JavaScript数组,它们只是具有一些特殊功能的对象。)
因此,将上面的线分解:
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
阅读一些关于和的文档怎么样?这就是文档和教程的用途。
var variableName = img[0].image;
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