【问题标题】:I am trying to fetch objects from a main object我正在尝试从主要对象中获取对象
【发布时间】:2015-07-10 12:20:04
【问题描述】:

我正在尝试从主对象中获取对象。主对象中的数组持有 这些其他对象,我可以通过调用'oData.events.event[0]'来访问第一个元素,但我想循环获取[1], [2], [3]等等。

//this works
var collection = oData.events.event[0];
$("<li>description: " + collection.description + "</li>").appendTo("#shower");


//this does not work :(

var collection = oData.events.event[0];

var output = "<ul>";

for (var i = 0; i < collection.length; i++)

{

    output += "<li>" + collection.description + "</li>";

    $(output).appendTo("#shower");

    collection = collection + 1 //shift to next array

}

output += "</ul>";

【问题讨论】:

    标签: javascript jquery arrays sorting stack


    【解决方案1】:

    也许使用 foreach 循环

    oData.events.event.forEach(function(result) {
        console.log(result);
    });
    

    或者,试试 jQuery 的 .each() 函数:

    $.each(oData.events.event, function(index, value) {
      console.log( index + ": " + value );
    });
    

    编辑:值得注意的是,这些调用的输出将是一个对象 - 您仍然必须访问您循环到的对象下方的数据!

    【讨论】:

      【解决方案2】:

      Fiddle 在这里 - 但是,你可以做这样的事情......

      var oData = {
          events: {
              event: [{ description: '1' },
                      { description: '2' },
                      { description: '3' }]
          }
      }
      
      var collection = oData.events.event;
      var output = "<ul>";
      
      collection.forEach(function(item, i, arr) {
          output += "<li>" + item.description + "</li>";
          if (i === arr.length-1) {
              output += "</ul>";
              $("#shower").append(output);
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-11
        • 2023-03-29
        • 1970-01-01
        • 2021-02-03
        • 1970-01-01
        • 2012-05-31
        • 2021-01-02
        相关资源
        最近更新 更多