迴圈提供一個快速又簡潔的方法來重複地做某件事。這個章節的JavaScript 教學會介紹在 JavaScript 可以使用的幾種不同的迭代陳述式。
你可以將迴圈想成一個電腦版本的"往一個方向走 X 步,然後往另一個方向走 Y 步"的遊戲;作為範例,"往東走五步"可以用這個方法用迴圈表示:
var step;
for (step = 0; step < 5; step++) {
// 執行五次:從step為0到4
console.log("Walking east one step");
}
有很多種不同種類的迴圈, 不過他們本質上都是做一樣的事:把一件動作重複地做一定的次數(而且也有可能做 0 次)。 各式各樣的迴圈機制提供了不同的方法來定義該迴圈的起始與結束。有些不同的情況下使用其中一種迴圈會比使用別種容易許多。
在 javaScript 中提供的迴圈陳述式分別為:
一個for 迴圈不斷重複直到一個指定的條件式判斷為 false。JavaScript 的 for 迴圈跟 Java 還有 C 的 for 迴圈很相似。一個 for 陳述式看起來像下面這樣:
for ([初始表達式]; [條件式]; [遞增表達式])
陳述式
當執行一個 for 迴圈時,會發生以下:
- 如果有的話,初始表達式會被執行。這個表達式通常會初始化一或多個迴圈計數器,但是語法允許任何程度的複雜性。這個表達式也能用來宣告變數。
- 條件式會被評估。如果評估出的值為 true,迴圈的敘事式便會執行。如果評估出的值為 false,這個 for 迴圈便會中止。如果條件式被省略了,狀態就會被假設是 true。
- 執行敘事式。要執行多個敘事式時,使用區塊敘事式(
{ ... }
) 來把那些敘事式歸為一組。
- 如果有更新表達式的遞增表達式便執行。然後 return 到第二步。
以下的函式包含一個用來數在一個滾動列表中被選過的選項(a <select>
允許複數選項的元素)的 for 陳述式 。這個 for 敘事式宣告了變數 i 並將其初始化為 0。 他檢查 i ,如果 i 少於在<select>元素中的選項數量,進行接著的 if 陳述式,並將 i 在每次通過迴圈後遞增。
<form name="selectForm">
<p>
<label for="musicTypes"
>Choose some music types, then click the button below:</label
>
<select id="musicTypes" name="musicTypes" multiple="multiple">
<option selected="selected">R&B</option>
<option>Jazz</option>
<option>Blues</option>
<option>New Age</option>
<option>Classical</option>
<option>Opera</option>
</select>
</p>
<p><input id="btn" type="button" value="How many are selected?" /></p>
</form>
<script>
function howMany(selectObject) {
var numberSelected = 0;
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
var btn = document.getElementById("btn");
btn.addEventListener("click", function () {
alert(
"Number of options selected: " + howMany(document.selectForm.musicTypes),
);
});
</script>
do...while
陳述式會不斷重複直到一個特定的條件判斷為 false。一個 do...while 陳述式看起來像以下:
do
陳述式
while (條件式);
陳述式會在檢查條件式以前先執行一次。要執行多個陳述式的話,使用區塊陳述式來將那些陳述式歸為一組。如果條件式為true,那陳述式便再次執行。在每次執行的最後,條件會被檢查。當條件式為false時,
停止執行並把控制傳給 do...while接著的陳述式。
在下列範例中,do 迴圈重複了至少一次並不斷重複直到 i 不再比 5 少。
var i = 0;
do {
i += 1;
console.log(i);
} while (i < 5);
while
陳述式會不斷執行它的陳述式只要指定的條件式判斷為 true。一個 while 陳述式看起來如下:
while (condition)
statement
如果條件式變成 false ,在迴圈中的陳述式會停止執行並控制交給跟在這個迴圈後面的陳述式。
條件式的測試發生於迴圈內的陳述式執行之前。如果條件式傳回 true ,陳述式便會被執行而判斷式會再被測試一次。如果條件式傳回 false ,停止執行並把控制交給跟在 while 迴圈後面的陳述式。
要執行多個陳述式的話,使用區塊陳述式來將那些陳述式歸為一組。
以下的 while 迴圈在只要 n 比 3 少的情況下便會不斷重複:
var n = 0;
var x = 0;
while (n < 3) {
n++;
x += n;
}
在每次的疊代,迴圈把 n 遞增並將其值加到 x 上。因此,x 跟 n 的值會是下列情況:
- 經過第一次迴圈後
n
= 1 而 x
= 1
- 經過第二次迴圈後
n
= 2 而 x
= 3
- 經過第三次迴圈後
n
= 3 而 x
= 6
在完成第三次迴圈後,判斷是 n<3 不再是 true ,所以迴圈終止。
避免無限迴圈。確定在迴圈內的判斷式終究會變成 false; 不然迴圈會永遠不終止。在迴圈內的陳述式會永遠的執行因為判斷式永遠不會變成 false:
while (true) {
console.log("Hello, world");
}
label 提供一個有識別字的陳述式讓你能在程式的別的地方參考。舉個例子,你能使用 label 來識別一個迴圈,然後使用 break 或 continue 陳述式來指示何時程式該中斷迴圈或是繼續他的執行。
label 陳述式的語法看起來如下:
label :
statement
Label 的值可以是任何不是保留字的 JavaScript 識別字。你用 label 所識別的陳述式可以是任何陳述式。
在這個範例,markLoop這個label 識別一個while 迴圈。
markLoop: while (theMark == true) {
doSomething();
}
break
陳述式是用來終止一個迴圈,一個 switch 多重控制選項,或是和一個 label 陳述式聯合使用。
- 當你在沒有 label 的情況下使用 break,它會馬上終止最內部的 while , do-while , for ,或是 switch 區間並將控制交給接下來的陳述式。
- 當你跟 label 一起使用的時候,它會終止那個特定的被 label 的陳述式。
break 陳述式的語法看起來如下:
break;
break label;
第一種語法會終止最內部的迴圈或 switch 區間;第二種語法會終止那個特定的 label 陳述式。
以下的範例會不斷重複跑迴圈直到有在陣列裡的元素符合 theValue 的值:
for (var i = 0; i < a.length; i++) {
if (a[i] == theValue) {
break;
}
}
var x = 0;
var z = 0;
labelCancelLoops: while (true) {
console.log("Outer loops: " + x);
x += 1;
z = 1;
while (true) {
console.log("Inner loops: " + z);
z += 1;
if (z === 10 && x === 10) {
break labelCancelLoops;
} else if (z === 10) {
break;
}
}
}
continue
陳述式可以用於重新開始一個 while , do-while, for, 或 label 陳述式。
- 當你在沒有 label 的情況下使用 continue,它會終止現在最內部 while, do-while , for 陳述式區間的迭代並繼續執行該迴圈的下一個迭代。跟 break 陳述式不同的是,continue 不會把整個迴圈的執行給終止。在 while 迴圈中,它會跳回條件式的判斷。在 for 迴圈中,它會跳至遞增陳述式。
- 當 contunue 跟 label 一起使用的時候,它會應用至被 label 識別的那個迴圈陳述式。
continue 陳述式的語法看起來如下:
continue;
continue
label;
以下的範例有 while 迴圈以及一個在 i 的值為 3 的時候執行的 continue 陳述式。因此,n 的值會連著是 1, 3, 7, 12。
var i = 0;
var n = 0;
while (i < 5) {
i++;
if (i == 3) {
continue;
}
n += i;
}
一個被 label 成 checkiandj 的陳述式包還著一個被 label 成 checkj 的陳述式。如果遇到了 continue,程式會終止現在的這輪迴圈並開始下一輪。每次遇到 continue,checkj 就會一直重複直到它的條件式返回 false。當 false 被傳回時,checkiandj 陳述式剩下的陳述式已被完成,而 checkiandj 也會繼續重複直到它的條件式傳回 false。當 false 被傳回,程式會繼續進行接著 checkiandj 後面的陳述式。
如果 continue 有了 checkiandj 的 label 程式會從 checkiandj 陳述式的頭開始繼續。
checkiandj: while (i < 4) {
console.log(i);
i += 1;
checkj: while (j > 4) {
console.log(j);
j -= 1;
if (j % 2 == 0) {
continue checkj;
}
console.log(j + " is odd.");
}
console.log("i = " + i);
console.log("j = " + j);
}
for...in
陳述式重複一個指定的變數來循環一個物件所有可枚舉的屬性。至於每個獨特的屬性,JavaScript 執行特定的陳述式。一個for...in
陳述式看起來像以下:
for (variable in object) {
statements
}
以下的函式透過它的參數得到一個物件和物件的名字。接著它循環這個物件的所有屬性並傳回一個列出屬性名和值的字串。
function dump_props(obj, obj_name) {
var result = "";
for (var i in obj) {
result += obj_name + "." + i + " = " + obj[i] + "<br>";
}
result += "<hr>";
return result;
}
對於一個擁有 make 跟 model 屬性的物件 car 來說,執行結果是:
car.make = Ford;
car.model = Mustang;
雖然用 for...in 來迭代 Array
元素很吸引人,但是它傳回的除了數字的索引之外還有可能是你自己定的屬性名。因此還是用帶有數字索引的傳統for迴圈來迭帶一個陣列會比較好。因為如果你想改變陣列物件,比如增加屬性或是方法,
for...in 陳述式迭代的是自定的屬性而不是陣列的元素。
for...of
陳述式在iterable objects(可迭代的物件)上建立了一個循環 (包含 Array
, Map
, Set
, arguments(參數) 物件 等等), 對每個獨特屬性的值使用一個準備被執行的有陳述式的自訂迭代掛勾。
for (variable of object) {
statement
}
下列的範例可看出for...of
迴圈跟 for...in
迴圈的差別。 for...in
在屬性名字循環,而for...of
在屬性的值循環。
let arr = [3, 5, 7];
arr.foo = "hello";
for (let i in arr) {
console.log(i); // logs "0", "1", "2", "foo"
}
for (let i of arr) {
console.log(i); // logs 3, 5, 7
}
\n"}},{"type":"prose","value":{"id":"do...while_陳述式","title":"do...while
陳述式","isH3":false,"content":"do...while
陳述式會不斷重複直到一個特定的條件判斷為 false。一個 do...while 陳述式看起來像以下:
\ndo\n 陳述式\nwhile (條件式);\n
\n陳述式會在檢查條件式以前先執行一次。要執行多個陳述式的話,使用區塊陳述式來將那些陳述式歸為一組。如果條件式為true,那陳述式便再次執行。在每次執行的最後,條件會被檢查。當條件式為false時,
停止執行並把控制傳給 do...while接著的陳述式。
"}},{"type":"prose","value":{"id":"範例_2","title":"範例","isH3":true,"content":"在下列範例中,do 迴圈重複了至少一次並不斷重複直到 i 不再比 5 少。
\nvar i = 0;\ndo {\n i += 1;\n console.log(i);\n} while (i < 5);\n
"}},{"type":"prose","value":{"id":"while_陳述式","title":"while
陳述式","isH3":false,"content":"while
陳述式會不斷執行它的陳述式只要指定的條件式判斷為 true。一個 while 陳述式看起來如下:
\nwhile (condition)\n statement\n
\n如果條件式變成 false ,在迴圈中的陳述式會停止執行並控制交給跟在這個迴圈後面的陳述式。
\n條件式的測試發生於迴圈內的陳述式執行之前。如果條件式傳回 true ,陳述式便會被執行而判斷式會再被測試一次。如果條件式傳回 false ,停止執行並把控制交給跟在 while 迴圈後面的陳述式。
\n要執行多個陳述式的話,使用區塊陳述式來將那些陳述式歸為一組。
"}},{"type":"prose","value":{"id":"範例_1","title":"範例 1","isH3":true,"content":"以下的 while 迴圈在只要 n 比 3 少的情況下便會不斷重複:
\nvar n = 0;\nvar x = 0;\nwhile (n < 3) {\n n++;\n x += n;\n}\n
\n在每次的疊代,迴圈把 n 遞增並將其值加到 x 上。因此,x 跟 n 的值會是下列情況:
\n\n- 經過第一次迴圈後
n
= 1 而 x
= 1 \n- 經過第二次迴圈後
n
= 2 而 x
= 3 \n- 經過第三次迴圈後
n
= 3 而 x
= 6 \n
\n在完成第三次迴圈後,判斷是 n<3 不再是 true ,所以迴圈終止。
"}},{"type":"prose","value":{"id":"範例_3","title":"範例 2","isH3":true,"content":"避免無限迴圈。確定在迴圈內的判斷式終究會變成 false; 不然迴圈會永遠不終止。在迴圈內的陳述式會永遠的執行因為判斷式永遠不會變成 false:
\nwhile (true) {\n console.log(\"Hello, world\");\n}\n
"}},{"type":"prose","value":{"id":"label_陳述式","title":"label
陳述式","isH3":false,"content":"label 提供一個有識別字的陳述式讓你能在程式的別的地方參考。舉個例子,你能使用 label 來識別一個迴圈,然後使用 break 或 continue 陳述式來指示何時程式該中斷迴圈或是繼續他的執行。
\nlabel 陳述式的語法看起來如下:
\nlabel :\n statement\n
\nLabel 的值可以是任何不是保留字的 JavaScript 識別字。你用 label 所識別的陳述式可以是任何陳述式。
"}},{"type":"prose","value":{"id":"範例_4","title":"範例","isH3":true,"content":"在這個範例,markLoop這個label 識別一個while 迴圈。
\nmarkLoop: while (theMark == true) {\n doSomething();\n}\n
"}},{"type":"prose","value":{"id":"break_陳述式","title":"break
陳述式","isH3":false,"content":"break
陳述式是用來終止一個迴圈,一個 switch 多重控制選項,或是和一個 label 陳述式聯合使用。
\n\n- 當你在沒有 label 的情況下使用 break,它會馬上終止最內部的 while , do-while , for ,或是 switch 區間並將控制交給接下來的陳述式。
\n- 當你跟 label 一起使用的時候,它會終止那個特定的被 label 的陳述式。
\n
\nbreak 陳述式的語法看起來如下:
\n\nbreak;
\nbreak label;
\n
\n第一種語法會終止最內部的迴圈或 switch 區間;第二種語法會終止那個特定的 label 陳述式。
"}},{"type":"prose","value":{"id":"範例_5","title":"範例 1","isH3":true,"content":"以下的範例會不斷重複跑迴圈直到有在陣列裡的元素符合 theValue 的值:
\nfor (var i = 0; i < a.length; i++) {\n if (a[i] == theValue) {\n break;\n }\n}\n
"}},{"type":"prose","value":{"id":"範例_2:break_至一個_label_陳述式","title":"範例 2:Break 至一個 label 陳述式","isH3":true,"content":"var x = 0;\nvar z = 0;\nlabelCancelLoops: while (true) {\n console.log(\"Outer loops: \" + x);\n x += 1;\n z = 1;\n while (true) {\n console.log(\"Inner loops: \" + z);\n z += 1;\n if (z === 10 && x === 10) {\n break labelCancelLoops;\n } else if (z === 10) {\n break;\n }\n }\n}\n
"}},{"type":"prose","value":{"id":"continue_陳述式","title":"continue
陳述式","isH3":false,"content":"continue
陳述式可以用於重新開始一個 while , do-while, for, 或 label 陳述式。
\n\n- 當你在沒有 label 的情況下使用 continue,它會終止現在最內部 while, do-while , for 陳述式區間的迭代並繼續執行該迴圈的下一個迭代。跟 break 陳述式不同的是,continue 不會把整個迴圈的執行給終止。在 while 迴圈中,它會跳回條件式的判斷。在 for 迴圈中,它會跳至遞增陳述式。
\n- 當 contunue 跟 label 一起使用的時候,它會應用至被 label 識別的那個迴圈陳述式。
\n
\ncontinue 陳述式的語法看起來如下:
\n\ncontinue;
\ncontinue
label;
\n
"}},{"type":"prose","value":{"id":"範例_6","title":"範例 1","isH3":true,"content":"以下的範例有 while 迴圈以及一個在 i 的值為 3 的時候執行的 continue 陳述式。因此,n 的值會連著是 1, 3, 7, 12。
\nvar i = 0;\nvar n = 0;\nwhile (i < 5) {\n i++;\n if (i == 3) {\n continue;\n }\n n += i;\n}\n
"}},{"type":"prose","value":{"id":"範例_7","title":"範例 2","isH3":true,"content":"一個被 label 成 checkiandj 的陳述式包還著一個被 label 成 checkj 的陳述式。如果遇到了 continue,程式會終止現在的這輪迴圈並開始下一輪。每次遇到 continue,checkj 就會一直重複直到它的條件式返回 false。當 false 被傳回時,checkiandj 陳述式剩下的陳述式已被完成,而 checkiandj 也會繼續重複直到它的條件式傳回 false。當 false 被傳回,程式會繼續進行接著 checkiandj 後面的陳述式。
\n如果 continue 有了 checkiandj 的 label 程式會從 checkiandj 陳述式的頭開始繼續。
\ncheckiandj: while (i < 4) {\n console.log(i);\n i += 1;\n checkj: while (j > 4) {\n console.log(j);\n j -= 1;\n if (j % 2 == 0) {\n continue checkj;\n }\n console.log(j + \" is odd.\");\n }\n console.log(\"i = \" + i);\n console.log(\"j = \" + j);\n}\n
"}},{"type":"prose","value":{"id":"for...in_陳述式","title":"for...in
陳述式","isH3":false,"content":"for...in
陳述式重複一個指定的變數來循環一個物件所有可枚舉的屬性。至於每個獨特的屬性,JavaScript 執行特定的陳述式。一個for...in
陳述式看起來像以下:
\nfor (variable in object) {\n statements\n}\n
"}},{"type":"prose","value":{"id":"範例_8","title":"範例","isH3":true,"content":"以下的函式透過它的參數得到一個物件和物件的名字。接著它循環這個物件的所有屬性並傳回一個列出屬性名和值的字串。
\nfunction dump_props(obj, obj_name) {\n var result = \"\";\n for (var i in obj) {\n result += obj_name + \".\" + i + \" = \" + obj[i] + \"
\";\n }\n result += \"
\";\n return result;\n}\n
\n對於一個擁有 make 跟 model 屬性的物件 car 來說,執行結果是:
\ncar.make = Ford;\ncar.model = Mustang;\n
"}},{"type":"prose","value":{"id":"陣列","title":"陣列","isH3":true,"content":"雖然用 for...in 來迭代 Array
元素很吸引人,但是它傳回的除了數字的索引之外還有可能是你自己定的屬性名。因此還是用帶有數字索引的傳統for迴圈來迭帶一個陣列會比較好。因為如果你想改變陣列物件,比如增加屬性或是方法,
for...in 陳述式迭代的是自定的屬性而不是陣列的元素。
"}},{"type":"prose","value":{"id":"for...of_陳述式","title":"for...of
陳述式","isH3":false,"content":"for...of
陳述式在iterable objects(可迭代的物件)上建立了一個循環 (包含 Array
, Map
, Set
, arguments(參數) 物件 等等), 對每個獨特屬性的值使用一個準備被執行的有陳述式的自訂迭代掛勾。
\nfor (variable of object) {\n statement\n}\n
\n下列的範例可看出for...of
迴圈跟 for...in
迴圈的差別。 for...in
在屬性名字循環,而for...of
在屬性的值循環。
\nlet arr = [3, 5, 7];\narr.foo = \"hello\";\n\nfor (let i in arr) {\n console.log(i); // logs \"0\", \"1\", \"2\", \"foo\"\n}\n\nfor (let i of arr) {\n console.log(i); // logs 3, 5, 7\n}\n
\n"}}],"isActive":true,"isMarkdown":true,"isTranslated":true,"locale":"zh-TW","mdn_url":"/zh-TW/docs/Web/JavaScript/Guide/Loops_and_iteration","modified":"2025-07-16T08:46:44.000Z","native":"正體中文 (繁體)","noIndexing":false,"other_translations":[{"locale":"en-US","title":"Loops and iteration","native":"English (US)"},{"locale":"de","title":"Schleifen und Iterationen","native":"Deutsch"},{"locale":"es","title":"Bucles e iteración","native":"Español"},{"locale":"fr","title":"Boucles et itérations","native":"Français"},{"locale":"ja","title":"ループと反復処理","native":"日本語"},{"locale":"ko","title":"루프와 반복","native":"한국어"},{"locale":"pt-BR","title":"Laços e iterações","native":"Português (do Brasil)"},{"locale":"ru","title":"Циклы и итерации","native":"Русский"},{"locale":"zh-CN","title":"循环与迭代","native":"中文 (简体)"}],"pageTitle":"Loops and iteration - JavaScript | MDN","parents":[{"uri":"/zh-TW/docs/Web","title":"給開發者的 Web 技術文件"},{"uri":"/zh-TW/docs/Web/JavaScript","title":"JavaScript"},{"uri":"/zh-TW/docs/Web/JavaScript/Guide","title":"JavaScript 指南"},{"uri":"/zh-TW/docs/Web/JavaScript/Guide/Loops_and_iteration","title":"Loops and iteration"}],"popularity":null,"short_title":"Loops and iteration","sidebarHTML":"- JavaScript
- Tutorials and guides
Beginner's tutorials
- Your first website: Adding interactivity
- Dynamic scripting with JavaScript
- JavaScript frameworks and libraries
JavaScript Guide
- Introduction
- Grammar and types
- Control flow and error handling
- Loops and iteration
- Functions
- Expressions and operators
- Numbers and strings
- Representing dates & times
- Regular expressions
- Indexed collections
- Keyed collections
- Working with objects
- Using classes
- Using promises
- JavaScript typed arrays
- Iterators and generators
- Resource management
- Internationalization
- JavaScript modules
Intermediate
- Advanced JavaScript objects
- Asynchronous JavaScript
- Client-side web APIs
- Language overview
- JavaScript data structures
- Equality comparisons and sameness
- Enumerability and ownership of properties
- Closures
Advanced
- Inheritance and the prototype chain
- Meta programming
- Memory Management
- References
Built-in objects
- AggregateError
- Array
- ArrayBuffer
- AsyncDisposableStack
- AsyncFunction
- AsyncGenerator
- AsyncGeneratorFunction
- AsyncIterator
- Atomics
- BigInt
- BigInt64Array
- BigUint64Array
- Boolean
- DataView
- Date
- decodeURI()
- decodeURIComponent()
- DisposableStack
- encodeURI()
- encodeURIComponent()
- Error
- escape()\n已棄用\n
- eval()
- EvalError
- FinalizationRegistry
- Float16Array
- Float32Array
- Float64Array
- Function
- Generator
- GeneratorFunction
- globalThis
- Infinity
- Int8Array
- Int16Array
- Int32Array
- InternalError\nNon-standard\n
- Intl
- isFinite()
- isNaN()
- Iterator
- JSON
- Map
- Math
- NaN
- Number
- Object
- parseFloat()
- parseInt()
- Promise
- Proxy
- RangeError
- ReferenceError
- Reflect
- RegExp
- Set
- SharedArrayBuffer
- 字串
- SuppressedError
- Symbol
- SyntaxError
- Temporal\n實驗性質\n
- TypedArray
- TypeError
- Uint8Array
- Uint8ClampedArray
- Uint16Array
- Uint32Array
- undefined
- unescape()\n已棄用\n
- URIError
- WeakMap
- WeakRef
- WeakSet
Expressions & operators
- 加法(+)
- Addition assignment (+=)
- Assignment (=)
- async function expression
- async function* expression
- await
- Bitwise AND (&)
- Bitwise AND assignment (&=)
- Bitwise NOT (~)
- Bitwise OR (|)
- Bitwise OR assignment (|=)
- Bitwise XOR (^)
- Bitwise XOR assignment (^=)
- class expression
- Comma operator (,)
- 條件運算子
- 遞減運算子(--)
- 屬性的刪除
- 解構
- 相除運算子(/)
- Division assignment (/=)
- Equality (==)
- 指數運算子(**)
- Exponentiation assignment (**=)
- function expression
- function* expression
- Greater than (>)
- Greater than or equal (>=)
- Grouping operator ( )
- import.meta
- import.meta.resolve()
- import()
- in
- 遞增運算子(++)
- Inequality (!=)
- instanceof
- Left shift (<<)
- Left shift assignment (<<=)
- Less than (<)
- Less than or equal (<=)
- Logical AND (&&)
- Logical AND assignment (&&=)
- Logical NOT (!)
- Logical OR (||)
- Logical OR assignment (||=)
- 相乘運算子(*)
- Multiplication assignment (*=)
- 建構子函數的使用
- new.target
- null
- Nullish coalescing assignment (??=)
- Nullish coalescing operator (??)
- Object initializer
- 運算子優先序
- 可選串連
- Property accessors
- Remainder (%)
- Remainder assignment (%=)
- Right shift (>>)
- Right shift assignment (>>=)
- Spread syntax (...)
- Strict equality (===)
- Strict inequality (!==)
- 相減運算子(-)
- Subtraction assignment (-=)
- super
- this
- typeof
- 一元負號運算子(-)
- 一元正號(+)
- Unsigned right shift (>>>)
- Unsigned right shift assignment (>>>=)
- void operator
- yield
- yield*
Statements & declarations
- async function
- async function*
- await using
- 區塊
- break
- class
- const
- continue 語法
- debugger
- do...while 語法
- Empty statement
- export
- Expression statement
- for 語法
- for await...of
- for...in
- for...of
- function
- function*
- if...else
- import
- Import attributes
- label
- let
- return
- switch
- throw
- try...catch 語法
- using
- var
- while 語法
- with\n已棄用\n
Functions
- 箭頭函式
- 預設參數
- getter
- 方法定義
- 其餘參數
- setter
- The arguments object
- [Symbol.iterator]()
- callee\n已棄用\n
- length
Classes
- 建構子
- extends
- Private elements
- Public class fields
- static
- Static initialization blocks
Regular expressions
- Backreference: \\1, \\2
- Capturing group: (...)
- Character class escape: \\d, \\D, \\w, \\W, \\s, \\S
- Character class: [...], [^...]
- Character escape: \\n, \\u{...}
- Disjunction: |
- Input boundary assertion: ^, $
- Literal character: a, b
- Lookahead assertion: (?=...), (?!...)
- Lookbehind assertion: (?<=...), (?
- Modifier: (?ims-ims:...)
- Named backreference: \\k
- Named capturing group: (?...)
- Non-capturing group: (?:...)
- Quantifier: *, +, ?, {n}, {n,}, {n,m}
- Unicode character class escape: \\p{...}, \\P{...}
- Wildcard: .
- Word boundary assertion: \\b, \\B
Errors
- AggregateError: No Promise in Promise.any was resolved
- Error: Permission denied to access property \"x\"
- InternalError: too much recursion
- RangeError: argument is not a valid code point
- RangeError: BigInt division by zero
- RangeError: BigInt negative exponent
- RangeError: form must be one of 'NFC', 'NFD', 'NFKC', or 'NFKD'
- RangeError: invalid array length
- RangeError: invalid date
- RangeError: precision is out of range
- RangeError: radix must be an integer
- RangeError: repeat count must be less than infinity
- RangeError: repeat count must be non-negative
- RangeError: x can't be converted to BigInt because it isn't an integer
- ReferenceError: \"x\" is not defined
- ReferenceError: assignment to undeclared variable \"x\"
- ReferenceError: can't access lexical declaration 'X' before initialization
- ReferenceError: must call super constructor before using 'this' in derived class constructor
- ReferenceError: super() called twice in derived class constructor
- SyntaxError: 'arguments'/'eval' can't be defined or assigned to in strict mode code
- SyntaxError: \"0\"-prefixed octal literals are deprecated
- SyntaxError: \"use strict\" not allowed in function with non-simple parameters
- SyntaxError: \"x\" is a reserved identifier
- SyntaxError: \\ at end of pattern
- SyntaxError: a declaration in the head of a for-of loop can't have an initializer
- SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
- SyntaxError: arguments is not valid in fields
- SyntaxError: await is only valid in async functions, async generators and modules
- SyntaxError: await/yield expression can't be used in parameter
- SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions
- SyntaxError: character class escape cannot be used in class range in regular expression
- SyntaxError: continue must be inside loop
- SyntaxError: duplicate capture group name in regular expression
- SyntaxError: duplicate formal argument x
- SyntaxError: for-in loop head declarations may not have initializers
- SyntaxError: function statement requires a name
- SyntaxError: functions cannot be labelled
- SyntaxError: getter and setter for private name #x should either be both static or non-static
- SyntaxError: getter functions must have no arguments
- SyntaxError: identifier starts immediately after numeric literal
- SyntaxError: illegal character
- SyntaxError: import declarations may only appear at top level of a module
- SyntaxError: incomplete quantifier in regular expression
- SyntaxError: invalid assignment left-hand side
- SyntaxError: invalid BigInt syntax
- SyntaxError: invalid capture group name in regular expression
- SyntaxError: invalid character in class in regular expression
- SyntaxError: invalid class set operation in regular expression
- SyntaxError: invalid decimal escape in regular expression
- SyntaxError: invalid identity escape in regular expression
- SyntaxError: invalid named capture reference in regular expression
- SyntaxError: invalid property name in regular expression
- SyntaxError: invalid range in character class
- SyntaxError: invalid regexp group
- SyntaxError: invalid regular expression flag \"x\"
- SyntaxError: invalid unicode escape in regular expression
- SyntaxError: JSON.parse: bad parsing
- SyntaxError: label not found
- SyntaxError: missing : after property id
- SyntaxError: missing ) after argument list
- SyntaxError: missing ) after condition
- SyntaxError: missing ] after element list
- SyntaxError: missing } after function body
- SyntaxError: missing } after property list
- SyntaxError: missing = in const declaration
- SyntaxError: missing formal parameter
- SyntaxError: missing name after . operator
- SyntaxError: missing variable name
- SyntaxError: negated character class with strings in regular expression
- SyntaxError: new keyword cannot be used with an optional chain
- SyntaxError: nothing to repeat
- SyntaxError: numbers out of order in {} quantifier.
- SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code
- SyntaxError: parameter after rest parameter
- SyntaxError: private fields can't be deleted
- SyntaxError: property name __proto__ appears more than once in object literal
- SyntaxError: raw bracket is not allowed in regular expression with unicode flag
- SyntaxError: redeclaration of formal parameter \"x\"
- SyntaxError: reference to undeclared private field or method #x
- SyntaxError: rest parameter may not have a default
- SyntaxError: return not in function
- SyntaxError: setter functions must have one argument
- SyntaxError: string literal contains an unescaped line break
- SyntaxError: super() is only valid in derived class constructors
- SyntaxError: tagged template cannot be used with optional chain
- SyntaxError: Unexpected '#' used outside of class body
- SyntaxError: Unexpected token
- SyntaxError: unlabeled break must be inside loop or switch
- SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**'
- SyntaxError: use of super property/member accesses only valid within methods or eval code within methods
- SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
- TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed
- TypeError: 'x' is not iterable
- TypeError: \"x\" is (not) \"y\"
- TypeError: \"x\" is not a constructor
- TypeError: \"x\" is not a function
- TypeError: \"x\" is not a non-null object
- TypeError: \"x\" is read-only
- TypeError: already executing generator
- TypeError: BigInt value can't be serialized in JSON
- TypeError: calling a builtin X constructor without new is forbidden
- TypeError: can't access/set private field or method: object is not the right class
- TypeError: can't assign to property \"x\" on \"y\": not an object
- TypeError: can't convert BigInt to number
- TypeError: can't convert x to BigInt
- TypeError: can't define property \"x\": \"obj\" is not extensible
- TypeError: can't delete non-configurable array element
- TypeError: can't redefine non-configurable property \"x\"
- TypeError: can't set prototype of this object
- TypeError: can't set prototype: it would cause a prototype chain cycle
- TypeError: cannot use 'in' operator to search for 'x' in 'y'
- TypeError: class constructors must be invoked with 'new'
- TypeError: cyclic object value
- TypeError: derived class constructor returned invalid value x
- TypeError: getting private setter-only property
- TypeError: Initializing an object twice is an error with private fields/methods
- TypeError: invalid 'instanceof' operand 'x'
- TypeError: invalid Array.prototype.sort argument
- TypeError: invalid assignment to const \"x\"
- TypeError: Iterator/AsyncIterator constructor can't be used directly
- TypeError: matchAll/replaceAll must be called with a global RegExp
- TypeError: More arguments needed
- TypeError: null/undefined has no properties
- TypeError: property \"x\" is non-configurable and can't be deleted
- TypeError: Reduce of empty array with no initial value
- TypeError: setting getter-only property \"x\"
- TypeError: WeakSet key/WeakMap value 'x' must be an object or an unregistered symbol
- TypeError: X.prototype.y called on incompatible type
- URIError: malformed URI sequence
- Warning: -file- is being assigned a //# sourceMappingURL, but already has one
- Warning: unreachable code after return statement
Misc
- JavaScript technologies overview
- Execution model
- Lexical grammar
- Iteration protocols
- Strict mode
- Template literals
- Trailing commas
- Deprecated features
","sidebarMacro":"jssidebar","source":{"folder":"zh-tw/web/javascript/guide/loops_and_iteration","github_url":"https://github.com/mdn/translated-content/blob/main/files/zh-tw/web/javascript/guide/loops_and_iteration/index.md","last_commit_url":"https://github.com/mdn/translated-content/commit/7501a3e6e9bcdfde73809666161e9095d8097a0a","filename":"index.md"},"summary":"迴圈提供一個快速又簡潔的方法來重複地做某件事。這個章節的JavaScript 教學會介紹在 JavaScript 可以使用的幾種不同的迭代陳述式。","title":"Loops and iteration","toc":[{"text":"for
陳述式","id":"for_陳述式"},{"text":"do...while
陳述式","id":"do...while_陳述式"},{"text":"while
陳述式","id":"while_陳述式"},{"text":"label
陳述式","id":"label_陳述式"},{"text":"break
陳述式","id":"break_陳述式"},{"text":"continue
陳述式","id":"continue_陳述式"},{"text":"for...in
陳述式","id":"for...in_陳述式"},{"text":"for...of
陳述式","id":"for...of_陳述式"}],"pageType":"guide"}}