Typescript/javascript中的递归函数 [英] recursive functions in typescript/javascript
本文介绍了Typescript/javascript中的递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图递归调用以下函数.
I am trying to call the following function recursively.
public getData(key,value){
this.htmlString += '<span style="color:cornflowerblue">'+key+' </span>:';
if(value instanceof Object){
Object.keys(value).forEach(function (keydata) {
let obj = value[keydata];
this.getData(keydata,value[keydata]);
console.log(key,obj,obj instanceof Object)
});
}else{
this.htmlString += '<span>'+value+'</span>';
}
return this.htmlString;
};
当我尝试调用该函数时,它显示一个错误无法读取未定义的属性'getData'.代码中是否有任何错误或执行此操作的任何其他方式.
when i tried to call teh function it was showing an error " Cannot read property 'getData' of undefined. Is there any wrong in the code or any other way to do this.
推荐答案
forEach
接受回调,它是一个匿名函数,匿名函数中的 this
指的是<在非严格模式下为code> window ,在严格模式下为 undefined
.
forEach
accepts a callback, which is an anonymous function, and this
inside anonymous function refers to window
in non-strict mode or undefined
in strict mode.
您需要绑定上下文:
Object.keys(value).forEach(function (keydata) {
let obj = value[keydata];
this.getData(keydata,value[keydata]);
console.log(key,obj,obj instanceof Object)
}.bind(this));
或使用箭头功能:
Object.keys(value).forEach((keydata) => {
let obj = value[keydata];
this.getData(keydata,value[keydata]);
console.log(key,obj,obj instanceof Object)
});
或仅将指向 this
的指针作为 forEach
的第二个参数传递:
or simply pass pointer to this
as a second argument to forEach
:
Object.keys(value).forEach(function (keydata) {
let obj = value[keydata];
this.getData(keydata,value[keydata]);
console.log(key,obj,obj instanceof Object)
}, this);
这篇关于Typescript/javascript中的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文