Javascript 递归函数调用
我正在编写一个元素,它递归地从JSON对象构建菜单树。但是,当函数调用自身时,我得到一个错误:Javascript 递归函数调用,javascript,polymer,polymer-1.0,Javascript,Polymer,Polymer 1.0,我正在编写一个元素,它递归地从JSON对象构建菜单树。但是,当函数调用自身时,我得到一个错误:this.buildMenu不是一个函数 这是菜单 buildMenu: function(items) { var node = new Array(); items.forEach(function(elem,index,arr) { node.push(elem.Name); if (elem.SubBranch.length > 0) { return
this.buildMenu不是一个函数
这是菜单
buildMenu: function(items) {
var node = new Array();
items.forEach(function(elem,index,arr) {
node.push(elem.Name);
if (elem.SubBranch.length > 0) {
return this.buildMenu(elem.SubBranch); //error is here
}
});
return node;
}
handleRes: function() {
this.response = this.$.categoryList.lastResponse;
this.menuItems = this.buildMenu(this.response);
//...
}
调用buildMenu的原始方法
buildMenu: function(items) {
var node = new Array();
items.forEach(function(elem,index,arr) {
node.push(elem.Name);
if (elem.SubBranch.length > 0) {
return this.buildMenu(elem.SubBranch); //error is here
}
});
return node;
}
handleRes: function() {
this.response = this.$.categoryList.lastResponse;
this.menuItems = this.buildMenu(this.response);
//...
}
我已经验证了数据是否存在并且格式是否正确。如果我注释掉递归调用,我将得到第一层结果。因此,它在这方面起了作用
递归调用中调用的
elem.SubBranch
参数是一个数组,如果这很重要的话,它是完全有效的。问题是在forEach回调函数中,它引用了回调函数本身的上下文。然后,当调用this.buildMenu时,它会失败,因为该函数未在该上下文中定义
forEach函数接受一个参数,以提供使用this关键字时要使用的对象。在这种情况下,您可以使用以下代码:
buildMenu: function(items) {
var node = new Array();
items.forEach(function(elem,index,arr) {
node.push(elem.Name);
if (elem.SubBranch.length > 0) {
return this.buildMenu(elem.SubBranch); //error is here
}
}, this);
return node;
}
请注意回调后提供的这个参数。问题在于,在forEach回调函数中,它指的是回调函数本身的上下文。然后,当调用this.buildMenu时,它会失败,因为该函数未在该上下文中定义 forEach函数接受一个参数,以提供使用this关键字时要使用的对象。在这种情况下,您可以使用以下代码:
buildMenu: function(items) {
var node = new Array();
items.forEach(function(elem,index,arr) {
node.push(elem.Name);
if (elem.SubBranch.length > 0) {
return this.buildMenu(elem.SubBranch); //error is here
}
}, this);
return node;
}
请注意回调后提供的此参数。是否可以构建一个plunker来演示问题?是否可以构建plunker来演示问题?