How do I iterate over a JSON structure?

This question already has an answer here:

  • For-each over an array in JavaScript? 23 answers

  • 来自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);
      }
    }

    Use 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>
    

    Will result in:

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

    上一篇: 将属性添加到数组中的所有对象

    下一篇: 我如何迭代JSON结构?