Javascript 中 RangeError: Maximum call stack size exceeded 错误
“RangeError: Maximum call stack size exceeded”错误发生在函数被多次调用以至于调用超出调用堆栈限制时。 要解决该错误,需要指定退出递归必须满足的基本情况。
下面是错误发生的示例。
function example() {
// ⛔️ RangeError: Maximum call stack size exceeded
example();
}
example();
我们调用该函数,然后该函数调用自身,直到超过调用堆栈限制。
要解决此错误,需要指定函数停止调用自身的条件。
let counter = 0;
function example(num) {
if (num < 0) {
return; // 👈️ 这会阻止函数无休止地调用自己
}
counter += 1;
example(num - 1);
}
example(4);
console.log(counter); // 👉️ 5
这次我们检查每次调用时是否使用小于 0 的数字调用函数。
如果数字小于 0,我们只需从函数返回,这样就不会超过调用堆栈的限制。
如果传入的值不小于 0,我们调用传入的值减去 1 的函数。这使我们继续朝着满足 if 检查的情况前进。
递归函数调用自身,直到满足条件。 如果你的函数中没有条件满足,它将调用自己,直到超过最大调用堆栈大小。
如果我们有一个在某处调用函数的无限循环,我们也可能会收到此错误。
function sum(a, b) {
return a + b;
}
while (true) {
sum(10, 10);
}
我们的 while 循环不断调用该函数,并且由于我们没有退出循环的条件,我们最终超出了调用堆栈大小。
这与在没有基本条件的情况下调用自身的函数非常相似。 如果我们使用 for 循环,情况也是如此。
下面是一个示例,说明如何指定退出循环必须满足的条件。
function sum(a, b) {
return a + b;
}
let total = 0;
for (let i = 10; i > 0; i--) {
total += sum(5, 5);
}
console.log(total); // 👉️ 100
如果 i 变量等于或小于 0,则 for 循环中的条件不满足,所以我们退出循环。
如果我们无法准确跟踪错误发生的位置,请查看浏览器控制台或终端(如果使用 Node.js)中的错误消息。
如果我们多次导入同一个文件,也可能会发生错误,例如 在同一页面上多次加载 jQuery 脚本。
我们可以通过在浏览器的开发人员工具中打开“网络”选项卡并刷新页面来检查页面上加载了哪些脚本。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。