簡體   English   中英

JS:對象迭代失敗

[英]JS: Object iteration fails

在我的JS中,我有一個名為box_object的對象。 它看起來像這樣:

({  id:"3",
    text:"this is a box object",
    connection_parent:["1", "2"],
    connection_child:["5", "6"],
    connectiondata_child:{
        0:{id:"5", linepoint:"bottom"},
        1:{id:"6", linepoint:"bottom"}},
    connectiondata_parent:{
        0:{id:"1", linepoint:"top"},
        1:{id:"2", linepoint:"top"}}
})

現在,我想向box_object.connectiondata_parent添加一些位置值。 使用jQuery,我可以使用.each()方法。 所以我嘗試了一下,但是失敗了。 在我的職能中,請執行以下操作:

$(box_object.connectiondata_parent).each(function(it, obj){
    if(typeof(obj[it]) != "undefined" && obj[it].linepoint == "top"){
        var point_position_top = new Object();
        point_position_top.left = startingpoint_left;
        point_position_top.top = startingpoint_top;
        obj[it].position = point_position_top;
    }else if(typeof(obj[it]) != "undefined" && obj[it].linepoint == "bottom"){
        var point_position_bottom = new Object();
        point_position_bottom.left = startingpoint_left;
        point_position_bottom.top = startingpoint_bottom;
        obj[it].position = point_position_bottom;
    }else{}
});

在函數之后,我的box_object如下所示:

({ id:"3",
   text:"this is third box",
   connection_parent:["1", "2"],
   connection_child:["5", "6"],
   connectiondata_child:{
      0:{id:"5", linepoint:"bottom"},
      1:{id:"6", linepoint:"bottom"}},
   connectiondata_parent:{
      0:{id:"1", linepoint:"top", position:{left:500, top:104}},
      1:{id:"2", linepoint:"top"}}
})

似乎只將值寫入第一個“值”。 為什么?

根據Karl $(selector).each()此處$(selector).each()

這應該用於DOM元素。 對於普通對象或數組,請使用jQuery.each()

也許那就是給您帶來問題的原因。

以下代碼示例將對嵌套元素中的適當條目進行迭代並執行所請求的轉換,而不是為每種功能都使用框架。

function assert(cond, msg) {
  if (!cond) {
    throw msg + " ... failed";
  }
}

// assumed globals
var startingpoint_left   = 500;
var startingpoint_top    = 104;
var startingpoint_bottom =  50; // never shown in sample but referenced                                                         
var idx;

for (idx in box_object.connectiondata_parent) {
  if (box_object.connectiondata_parent.hasOwnProperty(idx)) {
    if (box_object.connectiondata_parent[idx]) {
      box_object.connectiondata_parent[idx].position = {
        "left": startingpoint_left,
        "top":  box_object.connectiondata_parent[idx].linepoint === "top" ? startingpoint_top : startingpoint_bottom
      };
    }
  }
}

assert(box_object.connectiondata_parent[0].position.top  === 104, "index 0 top ");
assert(box_object.connectiondata_parent[0].position.left === 500, "index 0 left");
assert(box_object.connectiondata_parent[1].position.top  === 104, "index 1 top ");
assert(box_object.connectiondata_parent[1].position.left === 500, "index 1 top ");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM