如何获取javascript数组中的第一个值

How to get the first value in a javascript array

本文关键字:数组 第一个 javascript 何获取 获取      更新时间:2023-09-26

我想获得下面声明的数组img中的第一个文件名(Apple_Desk_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比数组的length小一(。在这种情况下,这将为您提供对对象的引用。要访问对象的属性,可以使用上面提到的文字表示法(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
// dot notation
console.log(img[0].image);

或:

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

将为您获得它,因为您有一个对象数组。