【问题标题】:Loop over child objects循环子对象
【发布时间】:2015-07-22 13:04:51
【问题描述】:

我正在尝试使用 $(parent).each() 循环对象内的子对象,但它只会返回父对象。在下面的代码中,console.log() 都打印完全相同的内容。我想要的是遍历子“Rectangle”、“PointEnd”和“PointStart”对象,然后是它们的子对象。

moveItemsObjArray = [];
moveItemsObj = {};
mobeItemsObj.pointer = guidVarible;
moveItemsObj.nodes =  {"Rectangle":{
                          "RECT_X": lineRect_X,
                          "RECT_Y": lineRect_Y,
                          "RECT_W": lineRect_W,
                          "RECT_H": lineRect_H
                        },
                        "PointStart":{
                          "POINT_X": newPointStart_X,
                          "POINT_Y": newPointStart_Y
                        },
                        "PointEnd": {
                          "POINT_X": newPointEnd_X,
                          "POINT_Y": newPointEnd_Y
                        }
                      };
                      moveItemsObjArray.push(moveItemsObj);
});


$(moveItemsObjArray).each(function(){
  var nodes = this.nodes;
    console.log(nodes);
  $(nodes).each(function(){
    console.log(this);
  });
});

【问题讨论】:

    标签: javascript jquery object


    【解决方案1】:

    还有这个?

    $.each(nodes, function(i, node) {
        $.each(node, function(i, child) {
            console.log(child); // normal value
            console.log($(child)); // make jquery object
        });
    });
    

    在 vanilla js 中你可以使用for(var node in nodeObjects) 它将返回索引。 jQuery 在 .each 函数中同时具有 i, 值。

    两个例子都是here

    【讨论】:

    • 我需要遍历 Rectangle/Pointer 节点而不知道它们的名字。
    • 你想得到什么?键 => val 还是 val ?
    【解决方案2】:

    代替

    moveItemsObj.pointer = guidVarible;
    

    你用过

    mobeItemsObj.pointer = guidVarible;
    

    【讨论】:

    • 这毫无意义。
    【解决方案3】:
    $(moveItemsObjArray).each(function(){
      var nodes = this.nodes;
      for(var k in nodes)
      {
          var xxx = nodes[k]
          for(var x in xxx)
          {
              alert(xxx[x])
          }
      }
    });
    

    JSFiddle

    循环可以随意进行。

    【讨论】:

    • 不错,但是如果你使用 jquery,为什么要混合 vanilla js 和 jquery?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多