我尝试了一些递归编程。我有一个变量来跟踪我的深度 (d)。控制台日志是为了让我看看程序现在在哪里。
var Test = function(){
this.rekursiv = function(d){
this.d = d;
console.log("case 1 granted, d: " + this.d);
if( this.d < 3) {
console.log("going deeper..");
this.rekursiv(this.d + 1);
console.log("going back..");
}
console.log("d: " + this.d );
}
}
t = new Test();
t.rekursiv(0);
这是我的问题: 每当我深入一层时,我都会将“this.d + 1”传递到下一层。 然而,调试代码(使用 console.log)显示 d 不仅在一个级别/深度发生变化,而且在每个级别/深度发生变化。
为什么会这样呢?我怎样才能阻止代码这样做?
最佳答案
为什么不使用局部变量d
?
使用 this.d
,您可以设置 Test
实例的属性。并且随着 rekursiv
的结束,您不会将值更改回以前的值。
var Test = function () {
this.rekursiv = function(d) {
console.log("case 1 granted, d: " + d);
if (d < 3) {
console.log("going deeper..");
this.rekursiv(d + 1);
console.log("going back..");
}
console.log("d: " + d );
}
},
t = new Test;
t.rekursiv(0);
另一个解决方案是在函数 rekursiv
的开头增加 this.d
并在末尾减少它。
var Test = function () {
this.d = 0;
this.rekursiv = function() {
this.d++;
console.log("case 1 granted, d: " + this.d);
if (this.d < 3) {
console.log("going deeper..");
this.rekursiv();
console.log("going back..");
}
console.log("d: " + this.d );
this.d--;
}
},
t = new Test;
t.rekursiv();
关于javascript - javascript中递归编程中的变量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39319840/