json回参考 [英] json back reference
问题描述
function attach_back_reference(hierarchy,parent){
hierarchy.parent = parent;
for(var i in hierarchy){
if(jQuery.isPlainObject(hierarchy [i]))
attach_back_reference(hierarchy [i],hierarchy);
}
}
但这是给出错误。 超过最大调用堆栈大小
自从你
for(var i in hierarchy){
添加父
属性后,一个值 i
将为父母
,所以你最终可以无限制地将孩子设为自己的祖父母。
你可以在
var o = {};
o.x = o;
(var i in o){alert(i);
哪些提醒x
/ p>
将循环移动到顶部。
function attach_back_reference(hierarchy,父代){
for(var i in hierarchy){
if(jQuery.isPlainObject(hierarchy [i]))
attach_back_reference(hierarchy [i],hierarchy);
}
hierarchy.parent = parent;
}
或者,如果您只需要这样来处理较新的口译员,就可以尝试使父属性无可争辩: javascript defineProperty使属性不可枚举
I've a hierarchical json object, I want to traverse it and attach a parent node to each element. This is what I've done
function attach_back_reference(hierarchy, parent){
hierarchy.parent = parent;
for(var i in hierarchy){
if(jQuery.isPlainObject(hierarchy[i]))
attach_back_reference(hierarchy[i], hierarchy);
}
}
But this is giving error. Maximum call stack size exceeded
Since you do
for(var i in hierarchy){
after adding the parent
property, one value of i
will be "parent"
, so you end up setting the child as its own grandparent infinitely.
You can see this in
var o = {};
o.x = o;
for (var i in o) { alert(i); }
which alerts "x"
.
Move the loop to the top.
function attach_back_reference(hierarchy, parent){
for(var i in hierarchy){
if(jQuery.isPlainObject(hierarchy[i]))
attach_back_reference(hierarchy[i], hierarchy);
}
hierarchy.parent = parent;
}
Alternatively, if you only need this to work on newer interpreters, you can try making the parent property unenumerable : javascript defineProperty to make an attribute non enumerable
这篇关于json回参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!