下面的代码按预期得到错误 Maximum call stack size exceeded
。
function recurrent (i = 0) {
recurrent(++i)
}
recurrent ()
我预计这也超出了最大调用堆栈。 但是,它运行了,为什么?
function recurrent (i = 0) {
console.log(i)
recurrent(++i)
}
recurrent ()
结果:
打印到一个数字并停止,但没有错误。
...
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
我在 Windows 10 上使用 NodeJs 10
更新
最佳答案
正如人们所预料的那样,它们都会以完全相同的方式失败。只是日志语句将函数减慢到它可能不会立即失败的程度。
以下是使用 time
对每个版本进行计时的结果:
# With logging:
...
RangeError: Maximum call stack size exceeded
real 0m0.204s
user 0m0.171s
sys 0m0.035s
# Without logging
...
RangeError: Maximum call stack size exceeded
real 0m0.082s
user 0m0.054s
sys 0m0.021s
在 Chrome 中测试时会发生相同的过程,但是要慢得多。在抛出 RangeError
之前花了 30 多秒。
关于javascript - console.log 避免最大调用堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368236/