这种类型的递归在JavaScript中是不是很糟糕?如果是这样,我该如何重写呢? [英] Is this type of recursion bad in JavaScript? If so, how should I rewrite it?
问题描述
我的HTML代码如下所示:
I have HTML code that looks like this:
<body>
<label for="change0">What is your favorite number?</label>
<input type="text" id="change0" />
<div id="addStuff"></div>
<script src="scripts/main.js"></script>
</body>
我的JS看起来像这样:
And I have JS that looks like this:
/** @type {number} */
var counter = 1;
function doStuff(id) {
var thing = document.getElementById(id);
thing.addEventListener('change', doMoreStuff);
}
function doMoreStuff() {
counter++;
var addStuff = document.getElementById("addStuff");
var stuff = document.createElement("input");
stuff.id = "change" + counter;
stuff.type = "text";
addStuff.appendChild(stuff);
doStuff(stuff.id);
}
window.onload = function() {
/** @constant */
var SEED_ID = "change0"
doStuff(SEED_ID);
};
doMoreStuff()函数以递归方式调用doStuff()函数。 JavaScript是否正确管理内存,或者我做错了吗?
The doMoreStuff() function recursively calls the doStuff() function. Does JavaScript manage the memory properly, or am I doing this incorrectly?
推荐答案
doMoreStuff()函数递归调用doStuff()函数。
The doMoreStuff() function recursively calls the doStuff() function.
这不是真正的相互递归,因为 doStuff
不调用 doMoreStuff
- 它只将其设置为要调用的处理程序。
That's not really mutual recursion, as doStuff
doesn't call doMoreStuff
- it only sets it up as a handler to be called.
JavaScript是否正确管理内存
Does JavaScript manage the memory properly
是。异步递归(有时称为伪递归)不会增加调用堆栈,它就像尾递归一样。
Yes. Asynchronous "recursion" (sometimes dubbed pseudo-recursion) does not grow the call stack, it's much like tail recursion.
这篇关于这种类型的递归在JavaScript中是不是很糟糕?如果是这样,我该如何重写呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!