JavaScript 递归元素创建失败
我不明白为什么会失败:
var recursiveElementGenerator = function (elem_spec) {
elem = document.createElement(elem_spec.tag);
if (elem_spec.children) {
for (var i=0; i<elem_spec.children.length; i++) {
var c_elem = elem_spec.children[i];
var n_elem = recursiveElementGenerator(c_elem);
alert(elem===n_elem);
elem.appendChild(n_elem);
};
};
return elem;
};
elem_spec
对象具有标记和子属性,后者是类似对象的数组。
这会失败,因为递归调用返回的元素与递归调用之前创建的元素相同。我不明白 - 类似的版本可以工作,通过从数组上的 pop() 调用获取其标签值链,然后将其传递到递归调用中。
I don't understand why this fails:
var recursiveElementGenerator = function (elem_spec) {
elem = document.createElement(elem_spec.tag);
if (elem_spec.children) {
for (var i=0; i<elem_spec.children.length; i++) {
var c_elem = elem_spec.children[i];
var n_elem = recursiveElementGenerator(c_elem);
alert(elem===n_elem);
elem.appendChild(n_elem);
};
};
return elem;
};
The elem_spec
object has tag and children attributes, the latter being an array of similar objects.
This fails because the element returned by the recursive call is the same as the element created before that recursive call. Which I don't get -- a similar version works, by getting its chain of tag values from a pop() call on an array that is then passed into the recursive call.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用:
而不是:
不使用
var
关键字会使您的变量在全局范围内运行。使用它将在本地范围内创建变量,从它创建的行到函数定义的末尾。Try using:
instead of:
Not using the
var
keyword makes your variable operate on the global scope. Using it will create the variable in the local scope, from the line it's created to the end of your function definition.