我正在帮助某人完成他的学校作业 - 我们正在尝试编写递归函数(如果重要的话 - 使用 PHP 或 JavaScript)。
我很了解递归原理,但我还没有从“学术”的 Angular 写过任何递归原理。
使用全局变量存储结果是一种好习惯吗,比如:
var results = [];
var rec = function(a) {
...
if (match)
results.push(someValue);
}
或者我应该使用 return 将所有这些结果收集在一起(这会困难得多)?
最佳答案
最好使用尽可能少的全局变量,最好不使用1。
为了避免在递归中需要全局变量,您可以使用使用闭包的内部函数:
var rec = function(a) {
var someValue = [];
function dorec() {
// stuff happens
if (match)
results.push(someValue);
}
}
dorec();
}
All variables should be declared before used. JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that may become implied globals. Implied global variables should never be used. Use of global variables should be minimized.
关于javascript - 在递归中使用全局变量是一种好习惯吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26595562/