Looping statements
Looping statements give you the ability to run the same block of code over and over again. There are two fundamental looping mechanisms in JavaScript. The for loop executes a code block a specified number of times and the while loop executes a code block while a condition is true. Once the condition becomes false, the looping mechanism stops.
The syntax of a for loop is shown as follows. You'll note that it takes a start value for the loop counter that is an integer and a condition expression that, if it evaluates to false, will cause the loop to terminate. You should also supply an increment that increases the value of the loop counter on each iteration of the loop:
for (start value; condition statement; increment) { the code block to be executed }
In the following example, the start value is set to 0 and is assigned to a variable called i. The condition statement is when i is less than or equal to 10, and the value of i is incremented by 1 for each iteration of the loop using the ++ operator. The code in the body of the loop prints the value of i for the current iteration:
var i = 0; for (i = 0; i <= 10; i++) { document.write("The number is " + i); document.write("<br/>"); }
The other basic looping mechanism in JavaScript is the while loop. This loop is used when you want to execute a code block while a condition is true. Once the condition is set to false, execution stops. while loops accept a single argument which is the condition expression that will be tested. In the following example, the code block will execute while i is less than or equal to 10. Initially i is set to a value of 0. At the end of the code block you will notice that i is incremented by one (i = i + 1):
var i = 0; while (i <= 10) { document.write("The number is " + i); document.write("<br/>"); i = i + 1; }
The while loop repeats until i reaches the value of 11.
- SQL Server 2016從入門(mén)到精通(視頻教學(xué)超值版)
- arc42 by Example
- 深入淺出WPF
- MySQL數(shù)據(jù)庫(kù)基礎(chǔ)實(shí)例教程(微課版)
- 機(jī)器學(xué)習(xí)與R語(yǔ)言實(shí)戰(zhàn)
- Visual Basic程序設(shè)計(jì)
- 區(qū)塊鏈技術(shù)與應(yīng)用
- Java Web開(kāi)發(fā)就該這樣學(xué)
- Visual C#.NET Web應(yīng)用程序設(shè)計(jì)
- Flowable流程引擎實(shí)戰(zhàn)
- Qt5 C++ GUI Programming Cookbook
- 軟件工程基礎(chǔ)與實(shí)訓(xùn)教程
- Python數(shù)據(jù)可視化之美:專(zhuān)業(yè)圖表繪制指南(全彩)
- 從程序員角度學(xué)習(xí)數(shù)據(jù)庫(kù)技術(shù)(藍(lán)橋杯軟件大賽培訓(xùn)教材-Java方向)
- Android Sensor Programming By Example