【问题标题】:Parsing JSON nested array using JQuery使用 JQuery 解析 JSON 嵌套数组
【发布时间】:2015-06-15 07:01:30
【问题描述】:

我有一个 API 可以将以下 JSON 值作为字符串返回。

"[
    ["West Baton Rouge test hello world", "1"],
    ["LSU Parking \u0026 Transportation Services", "2"],
    ["demokljafsk", "3"],
    ["latest", "19"],
    ["Hello check", "20"],
    ["Dinesh Devkota", "21"],
    ["World", "22"],
    ["altered value.", "23"],
    ["Dinesh Devkota", "24"],
    ["Dinesh Devkota", "25"],
    ["Dinesh Devkota", "26"],
    ["Dinesh Devkota", "27"],
    ["Dinesh Devkota", "28"],
    ["Rocking Client", "29"],
    ["West Baton Rouge", "30"],
    ["Test Client", "31"]
]"

我很难尝试使用 JQuery 获取每个数组的第一个值并使用以下代码将其登录到控制台。

  $.get("/controller", function (data) {
        console.log("Data Loaded: " + data);
        for (var eachdata in data) {
            console.log(eachdata[0]);
        }
   });

我是 JQUERY 的新手,想知道什么是正确的方法。

【问题讨论】:

    标签: javascript jquery arrays json frontend


    【解决方案1】:

    不要将for..in 用于数组

    var data = [
        ["West Baton Rouge test hello world", "1"],
        ["LSU Parking \u0026 Transportation Services", "2"],
        ["demokljafsk", "3"],
        ["latest", "19"],
        ["Hello check", "20"],
        ["Dinesh Devkota", "21"],
        ["World", "22"],
        ["altered value.", "23"],
        ["Dinesh Devkota", "24"],
        ["Dinesh Devkota", "25"],
        ["Dinesh Devkota", "26"],
        ["Dinesh Devkota", "27"],
        ["Dinesh Devkota", "28"],
        ["Rocking Client", "29"],
        ["West Baton Rouge", "30"],
        ["Test Client", "31"]
    ];
    
    for (var i = 0, len = data.length; i < len; i++) {
       console.log(data[i][0]);
    }
    
    // with jQuery
    $.each(data, function (index, value) {
       console.log(value[0]);
    })
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案2】:
      $.get("/controller", function (data) {
          console.log("Data Loaded: " + data);
          for (var eachdata in data) {
              console.log(data[eachdata][0]);
          }
      });
      

      问题是for-in 返回键,而不是值。

      【讨论】:

        【解决方案3】:

        你可以这样做:

        for (var i=0; i<data.length; i++) {
            console.log(data[i][0]);
        }
        

        示例:http://jsfiddle.net/5db2h32g/1/

        【讨论】:

          【解决方案4】:

          由于您使用的是 jQuery,$.each 是一个非常有用的工具:

          $.each( data, function( arrayIndex, arrayElement) {
              console.log(arrayElement[0]);
          });
          

          用于数组时,回调的第一个参数是索引,第二个参数是数组元素。

          它还创建了一个闭包,在处理循环中的异步代码时非常有用

          参考jQuery.each() docs

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-02-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多