我如何迭代JSON结构?

这个问题在这里已经有了答案:

  • 对于JavaScript中的每个数组? 23个答案

  • 来自jQuery文档:

    var arr = [ "one", "two", "three", "four", "five" ];
    var obj = { one:1, two:2, three:3, four:4, five:5 };
    
    jQuery.each(arr, function() {
      $("#" + this).text("My id is " + this + ".");
      return (this != "four"); // will stop running to skip "five"
    });
    
    jQuery.each(obj, function(i, val) {
      $("#" + i).append(document.createTextNode(" - " + val));
    });
    

    var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}];
    
    for (var i = 0; i < arr.length; i++){
        var obj = arr[i];
        for (var key in obj){
            var attrName = key;
            var attrValue = obj[key];
        }
    }
    

    var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}];
        
    for (var i = 0; i < arr.length; i++){
      document.write("<br><br>array index: " + i);
      var obj = arr[i];
      for (var key in obj){
        var value = obj[key];
        document.write("<br> - " + key + ": " + value);
      }
    }

    使用foreach

    <html>
    <body>
    <script type="text/javascript">
    var mycars = [{name:'Susita'}, {name:'BMW'}];
    for (i in mycars)
    {
      document.write(mycars[i].name + "<br />");
    }
    </script>
    </body>
    </html>
    

    将导致:

    Susita
    BMW
    
    链接地址: http://www.djcxy.com/p/12051.html

    上一篇: How do I iterate over a JSON structure?

    下一篇: Python List Comprehension Vs. Map