2010-05-06 65 views
0

在我的JS中,我有一個名爲box_object的對象。 它看起來像這樣:JS:對象迭代失敗

({ 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"}} 
}) 

似乎只寫值第一個「值」。任何想法爲什麼?

回答

2

Karl Swedberg評論here,在$(selector).each()

這應該用於DOM元素。 對於普通物體或陣列,請使用 jQuery.each()

也許那就是給你一個問題。

+0

謝謝!只是爲了記錄:'$ .each(box_object.connectiondata_parent,function(it,obj){...}'然後使用obj而不是obj [it]。 – Newbie 2010-05-06 09:45:53

0

下面的代碼示例將對嵌套元素中的正確條目進行迭代並執行所請求的轉換,而不是使用每個功能的框架。

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 ");