JavaScript 错误InternalError too much recursion
函数调用次数过多,或者函数缺少基本情况时,会出现 too much recursion 或 堆栈溢出 的异常。
输出信息:
Error: Out of stack space (Edge)
InternalError: too much recursion (Firefox)
RangeError: Maximum call stack size exceeded (Chrome)
错误类型:
InternalError
一个 递归函数 是一个不断调用自身的函数。当满足某个条件时,函数停止调用自身,这被称为基本情况。如果条件不满足,则函数继续调用自身,错误就会发生。
示例1: 该示例完美地运行,没有错误。因为停止条件是x >= 5。
function recursion(x) {
// Base case
if (x >= 5)
return;
recursion(x + 1); // The recursive call
}
function Geeks() {
try {
recursion(0);
console.log("Too much "
+ "recursion error not occurred");
} catch (e) {
console.log("Too much "
+ "recursion error occurred");
}
}
Geeks();
输出
Too much recursion error not occurred
示例2: 在这个例子中,停止条件是当x >= 1000000000000。这是一个很大的值,所以发生了错误。
function recursion(x) {
// Base case
if (x >= 1000000000000)
return;
recursion(x + 1); // The recursive call
}
function Geeks() {
try {
recursion(0);
console.log("Too much recursion"
+ " error not occurred");
} catch (e) {
console.log("Too much recursion"
+ " error occurred");
}
}
Geeks();
输出
Too much recursion error occurred