blob: 1708683ffade658008bd5f31fb9dcd01f6728fe3 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
---
title: 'InternalError: too much recursion'
slug: Web/JavaScript/Reference/Errors/Too_much_recursion
translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion
---
<div>{{jsSidebar("Errors")}}</div>
<h2 id="訊息">訊息</h2>
<pre class="syntaxbox">InternalError: too much recursion
</pre>
<h2 id="錯誤類型">錯誤類型</h2>
<p>{{jsxref("InternalError")}}</p>
<h2 id="哪裡錯了?">哪裡錯了?</h2>
<p>一個呼叫自己的函式稱為<em>遞迴函式</em>(recursive function)。在某些方面,遞迴和迴圈很像。它們都需要在指定條件(以避免無窮迴圈,或是本例的無窮遞迴)下,重複執行數次相同的程式碼。如果遞迴執行太多次、或成為無窮遞迴的話,JavaScript 就會出現這個錯誤。</p>
<h2 id="實例">實例</h2>
<p>以下的遞迴函式,會根據終止條件,而運行十次。</p>
<pre class="brush: js">function loop(x) {
if (x >= 10) // "x >= 10" 是終止條件
return;
// do stuff
loop(x + 1); // 遞迴呼叫
}
loop(0);</pre>
<p>如果把終止條件的次數設得太高,函式就不會運作了:</p>
<pre class="brush: js example-bad">function loop(x) {
if (x >= 1000000000000)
return;
// do stuff
loop(x + 1);
}
loop(0);
// InternalError: too much recursion</pre>
<h2 id="參見">參見</h2>
<ul>
<li>{{Glossary("Recursion")}}</li>
<li><a href="/zh-TW/docs/Web/JavaScript/Guide/Functions#Recursion">遞迴函式</a></li>
</ul>
|