Javascript forEach只执行数组的最后一个元素
我在做一个新项目;类似于javaScript中的模板系统。 这是我的小代码:Javascript forEach只执行数组的最后一个元素,javascript,arrays,json,foreach,documentfragment,Javascript,Arrays,Json,Foreach,Documentfragment,我在做一个新项目;类似于javaScript中的模板系统。 这是我的小代码: var Tree = ( function ( _Obj ) { var _E, _N; _Obj.forEach ( function ( e ) { _E = document.createDocumentFragment(); if ( "tagName" in e ) { _N = document.createElement( e.tagName );
var Tree = ( function ( _Obj ) {
var _E,
_N;
_Obj.forEach ( function ( e ) {
_E = document.createDocumentFragment();
if ( "tagName" in e ) {
_N = document.createElement( e.tagName );
}
if ( "childNode" in e ) {
_N.appendChild( Tree ( e.childNode ) );
}
});
_E.appendChild ( _N );
return _E;
});
这里是该函数的参数:
Fragment = [{ // firstNode
"tagName" : "div",
"childNode" : [{
"tagName" : "p",
"childNode" : [{
"tagName" : "string",
"childNode" : [{
"tagName" : "span",
}]
}]
}]
},
{ //secondNode
"tagName" : "div",
"childNode" : [{
"tagName" : "p",
"childNode" : [{
"tagName" : "span",
"childNode" : [{
"tagName" : "div"
}]
}]
}]
}
];
嗯,;这段代码应该返回一个包含var片段的每个对象的文档片段;如果你看,JSON是基于标记名和子节点元素的;每个对象依赖一个标记名,因此函数返回一个同名新元素
但是这里出了点问题;函数仅返回var片段的第二个节点:
#document-fragment
|_<div>
|_<p>
|_<span>
<div></div>
</span>
</p>
</div>
但是,第一个节点发生了什么
感谢您的支持:)
PD:对不起,我的英语,我来自阿根廷。看起来你的forEach循环通过并将
\N
分配给正确的内容,但只有在整个循环通过后才将\N
附加到\E
。将您的\E.appendChild(\N)
移动到for each的内部和底部
var Tree = ( function ( _Obj ) {
var _E,
_N;
_E = document.createDocumentFragment(); // put this out of forEach
_Obj.forEach ( function ( e ) {
if ( "tagName" in e ) {
_N = document.createElement( e.tagName );
}
if ( "childNode" in e ) {
_N.appendChild( Tree ( e.childNode ) );
}
_E.appendChild ( _N ); // put this inside of forEach
});
return _E;
});
var Tree = ( function ( _Obj ) {
var _E,
_N;
_E = document.createDocumentFragment(); // put this out of forEach
_Obj.forEach ( function ( e ) {
if ( "tagName" in e ) {
_N = document.createElement( e.tagName );
}
if ( "childNode" in e ) {
_N.appendChild( Tree ( e.childNode ) );
}
_E.appendChild ( _N ); // put this inside of forEach
});
return _E;
});