JS:オブジェクトの反復は失敗します
-
03-10-2019 - |
質問
私の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"}}
})
値を最初の「値」に書き込むだけです。なんで?
解決
コメントによると ここ に カール・スウェドバーグ, 、 の上 $(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 ");
所属していません StackOverflow