这是我用 Javascript 编写的一个函数,用于说明我遇到的问题。
function test(x,depth){
for (n=0;n<x;n++){
console.log(x.toString()+" "+depth.toString()+" "+n.toString())
test(x-1,depth+1)
console.log(x.toString()+" "+depth.toString()+" "+n.toString())
}
}
test(4,0)
这是我的控制台输出:
4 0 0
3 1 0
2 2 0
1 3 0
1 3 0
2 2 1
3 1 2
4 0 3
为什么调用test(x-1,深度+1)会影响变量n? n 不作为参数传递。
谢谢
最佳答案
n
是全局的,通过 The Horror of Implicit Globals 创建* 第一次为其赋值 (n=0
) 时,这样所有对 test
的调用都会使用一个全局变量。您需要在 test
中声明它,使其成为本地的(因此每个调用都有自己的副本)。 (例如,添加 var
或在 ES2015+ 中添加 let
。)
* (这是我贫血的小博客上的一篇文章。)
关于javascript - js递归函数意外改变变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47515918/