获取json数组中的第4个元素

Get only the 4th element in json array

本文关键字:4个 元素 json 数组 获取      更新时间:2023-09-26

我有一个json文件,如下所示:

{
    "product": {
        images": [
         "13953115",
         "13953112",
         "13953116",
         "13953026",
         "13953021",
         "11519717" 
        ], //etc
   }
}

我试图得到只有第4个元素(在上面的例子"13953026"),然后用它来追加到一个div。代码目前看起来像这样:

 $.getJSON('url-to-product?format=json', function(data){
   var images = [];
   // how to select the fourth element?//
   var image = images[4];
   var fourthImage = $('<img src="'+ image +'" width="265" height="340" alt="" />');
   $('.con_images').html(fourthImage);
 });

我以为var image = images[4];会起作用,但显然不是。我在这里发现了一些有用的帖子,但我不知道如何将其纳入我的代码。

有谁能帮我一下吗?Thx…

我认为这样做没有任何问题:

$.getJSON('url-to-product?format=json', function(data){
   var image = data.product.images[3];
   var fourthImage = $('<img src="'+ image +'" width="265" height="340" alt="" />');
   $('.con_images').html(fourthImage);
});

请参见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

要访问数组中的第四个元素,

使用obj.product.images[3]

数组索引从0