在 Javascript 中递归创建子属性
create children properties recursively in Javascript
我正在尝试根据传递的参数创建子级深度 n
。
基本上,如果 n 为 4,则生成的对象应该是
parent.children.children.children.children
.
到目前为止我已经想到了这个:
parent = {}
function makechildren( current, depth ){
current['children']={}
while (depth>0){ {
str = JSON.stringify(current)
return makechildren(current, depth-1)
}
}
}
makechildren(parent, 4)
我测试了这段代码,它有效
parent={};
var obj;
function makechildren( current, depth){
if(depth>0)
{
current = JSON.parse(JSON.stringify(current).replace('{}','{"children":{}}'))
makechildren(current, depth-1);
}else{
obj = current;
return ;
}
}
console.log(obj)
我正在尝试根据传递的参数创建子级深度 n
。
基本上,如果 n 为 4,则生成的对象应该是
parent.children.children.children.children
.
到目前为止我已经想到了这个:
parent = {}
function makechildren( current, depth ){
current['children']={}
while (depth>0){ {
str = JSON.stringify(current)
return makechildren(current, depth-1)
}
}
}
makechildren(parent, 4)
我测试了这段代码,它有效
parent={};
var obj;
function makechildren( current, depth){
if(depth>0)
{
current = JSON.parse(JSON.stringify(current).replace('{}','{"children":{}}'))
makechildren(current, depth-1);
}else{
obj = current;
return ;
}
}
console.log(obj)