JavaScript While Döngüsü
- Previous Page JS Loop For Of
- Next Page JS Break
Koşul doğru olduğu sürece, döngü kod bloğunu sürekli olarak çalıştırabilir.
While Döngüsü
While döngüsü, belirtilen koşul doğru olduğu sürece kod bloğunu döngü içinde tekrar eder.
Gramer
while (Koşul) { Yürütülmesi gereken kod bloğu }
Example
Aşağıdaki örnekte, değişken (i) 10'dan küçük olduğu sürece döngü içindeki kod tekrar tekrar çalışır:
while (i < 10) { text += "数字是 " + i; i++; }
Koşulda kullanılan değişkenlere artırma yapmayı unutursanız, döngü asla sona ermez. Bu, tarayıcının çökmesine neden olabilir.
Do/While Döngüsü
Do/while döngüsü, while döngüsünün bir varyasyonudur. Bu döngü, koşulun doğru olup olmadığını kontrol etmeden önce bir kez kod bloğunu çalıştırır ve koşul doğru olduğu sürece döngü tekrar eder.
Gramer
do { Yürütülmesi gereken kod bloğu } while (Koşul);
Example
Aşağıdaki örnek, do/while döngüsünü kullanır. Bu döngü, koşul false olsa bile en az bir kez çalışır, çünkü kod bloğu koşul testinden önce çalışır:
do { text += "The number is " + i; i++; } while (i < 10);
Do not forget to increment the variable used in the condition, otherwise the loop will never end!
Comparison of For and While
If you have read the previous chapters about loops, you will find that the while loop is quite similar to the for loop, where statements 1 and 2 can be omitted.
The loop used in this example For LoopTo extract the car brands from the cars array:
Example
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var i = 0; var text = ""; for (;cars[i];) { text += cars[i] + "<br>"; i++; }
The loop used in this example While LoopTo extract the car brands from the cars array:
Example
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var i = 0; var text = ""; while (cars[i]) { text += cars[i] + "<br>"; i++; }
Textbook
For more information about JavaScript while statementFor more information about the knowledge, please read the relevant content in the Advanced JavaScript Tutorial:
- ECMAScript Iteration Statements
- Iteration statements, also known as loop statements. This section introduces the four iteration statements provided by ECMAScript.
- Previous Page JS Loop For Of
- Next Page JS Break