在我的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"}}
})
似乎它只将值写入第一个“值”。为什么呢?
答案 0 :(得分:2)
答案 1 :(得分: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 ");