如何从javascript调用数组?

时间:2017-01-12 04:21:20

标签: javascript jquery arrays json

我想调用数组但仍然失败。 这是我的JS

var dataLayer =
[
    {
        "id" : "993932",
        "name" : "Foo Bar",
        "total_price" : "867252",
        "Recommended" : 
        [
            {
                "hotel_name" : "Four Season",
                "tripadvisor_ratings" : "5.0"
            },
            {
                 "hotel_name" : "Amaris Hotel",
                 "tripadvisor_ratings" : "5.0"
            }
        ];

var a = "<div>"+ dataLayer.hotel_name +"</div>"

或者您可以登记https://jsfiddle.net/dedi_wibisono17/7fnzofg1/1/

结果是未定义。有人帮我吗? 谢谢

2 个答案:

答案 0 :(得分:3)

此处datalayer是一个对象数组,键Recommended也是一个对象数组,因此要访问它们,首先需要选择索引中的元素。

dataLayer[0]将获取数组中的第一个对象

中唯一的对象
{
        "id" : "993932",
        "name" : "Foo Bar",
        "total_price" : "867252",
        "Recommended" : [
         {
            "hotel_name" : "Four Season",
            "tripadvisor_ratings" : "5.0"
         },
         {
             "hotel_name" : "Amaris Hotel",
             "tripadvisor_ratings" : "5.0"
         }
         ]
    }

然后键Recommended也有一个对象数组

[
     {
        "hotel_name" : "Four Season",
        "tripadvisor_ratings" : "5.0"
     },
     {
         "hotel_name" : "Amaris Hotel",
         "tripadvisor_ratings" : "5.0"
     }
 ]

所以,你需要使用索引来访问它们。

dataLayer[0].Recommended[0]将选择第一个对象

{
     "hotel_name" : "Four Season",
     "tripadvisor_ratings" : "5.0"
}

dataLayer[0].Recommended[0].hotel_name选择密钥hotel_name

要迭代推荐的键阵列中的所有对象,您可以使用forEach

 dataLayer[0].Recommended.forEach(function(obj){
    console.log(obj.hotel_name);
  }); 

&#13;
&#13;
var dataLayer = [
 {
    "id" : "993932",
    "name" : "Foo Bar",
    "total_price" : "867252",
    "Recommended" : [
     {
        "hotel_name" : "Four Season",
        "tripadvisor_ratings" : "5.0"
     },
     {
         "hotel_name" : "Amaris Hotel",
         "tripadvisor_ratings" : "5.0"
     }
     ]
}
];

dataLayer[0].Recommended.forEach(function(obj){
  console.log(obj.hotel_name);
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

 var dataLayer = [
 {
    "id" : "993932",
    "name" : "Foo Bar",
    "total_price" : "867252",
    "Recommended" : [
     {
        "hotel_name" : "Four Season",
        "tripadvisor_ratings" : "5.0"
     },
     {
         "hotel_name" : "Amaris Hotel",
         "tripadvisor_ratings" : "5.0"
     }
     ]
}
];
alert(dataLayer[0].Recommended[0].hotel_name);
alert(dataLayer[0].Recommended[1].hotel_name);