使用$ .each迭代数组

时间:2015-10-12 06:53:38

标签: jquery arrays

我有以下JSON结构,并且我试图抓住这个标题'值

{
    "ok": true,
    "messages": [{
        "type": "message",
        "subtype": "file_share",
        "file": {
            "name": "Football_and_Hurling_Images.txt",
            "title": "Football and Hurling Images"
        }
    }]
}

2 个答案:

答案 0 :(得分:1)

如果有多个messages

,您可以像这样迭代

  var obj = {
    "ok": true,
    "messages": [{
      "type": "message",
      "subtype": "file_share",
      "file": {
        "name": "Football_and_Hurling_Images.txt",
        "title": "Football and Hurling Images"
      }
    }, {
      "type": "message2",
      "subtype": "file_share",
      "file": {
        "name": "Football_and_Hurling_Images.txt",
        "title": "Football and Hurling Images2"
      }
    }, {
      "type": "message3",
      "subtype": "file_share",
      "file": {
        "name": "Football_and_Hurling_Images.txt",
        "title": "Football and Hurling Images3"
      }
    }]
  }
  $.each(obj.messages, function(index, msg) {
    //console.log(msg);
    console.log(msg.file.title);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

答案 1 :(得分:0)

此代码适合您。

 YourJSON.messages[0].file.title;