w3pop.com :: ÍøÂçѧԺ :: JavaScript :: JS For Ñ»·
Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.
ÔÚJSÖеÄÑ»·ÓÃÀ´Öظ´Ö´ÐÐÖ¸¶¨´ÎÊýµÄ´úÂë»òµ±Ìõ¼þÎªÕæÊ±ÖØ¸´Ö´ÐС£
For loop[forÑ»·]
How to write a for loop. Use a For loop to run the same block of code a specified number of times.
ÔõÑùдһ¶ÎÑ»·¡£Ê¹ÓÃÑ»·À´Ö´ÐÐÖ¸¶¨´ÎÊýµÄÏàͬ´úÂë¿é
Looping through HTML headers[Ñ»·µÄHTML±êÌâ]
How to use the for loop to loop through the different HTML headers.
ÔõÑùʹÓÃforÑ»·À´Íê³É²»Í¬Ñù×ÓµÄHTML±êÌâ
Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
µ±Äãд´úÂëµÄʱºò»á¾³£ÒªÈÃÒ»¶Î´úÂëÒ»ÐÐÐеÄÖØ¸´Ö´ÐУ¬ÒªÍê³ÉÕâÑùµÄÈÎÎñ²»ÐèÒªÄãÌí¼ÓÖØ¸´µÄ´úÂ룬ÎÒÃÇֻҪʹÓÃÑ»·¾ÍÐС£
In JavaScript there are two different kind of loops:
ÔÚJSÖÐÓÐÁ½ÖÖÑ»·£º
The for loop is used when you know in advance how many times the script should run.
ʹÓÃforÑ»·Ò»°ãÊǵ±ÄãÊÂÏÈÖªµÀ½Å±¾Ó¦¸ÃÖ´Ðм¸´Î¡£
Syntax
Óï·¨
for (var=startvalue;var<=endvalue;var=var+increment) |
Example
Àý×Ó
Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
ÊÍÒ壺ÏÂÃæµÄÀý×Ó¶¨ÒåÁËÒ»¸ö¿ªÊ¼i=0µÄÑ»·.Ñ»·»áÒ»Ö±ÔËÐÐÏÂÈ¥Ö±µ½i´óÓÚ10.iÿ´ÎÑ»·»áµÝÔö1
Note: The increment parameter could also be negative, and the <= could be any comparing statement.
×¢Ò⣺µÝÔöµÄ²ÎÊý»¹¿ÉÒÔÊǵݼõµÄ£¬<=ÊÇ¿ÉÒÔ»»³ÉÆäËûµÄÈκβÙ×÷·û¡£
<html> |
Result
£¨ÔËÐкóµÄ½á¹ûΪ£©
The number is 0 |
The while loop will be explained in the next chapter.
while / loop Ñ»·Óï¾ä½«ÔÚÏÂÒ»ÕÂ×÷¾ßÌå½²½â¡£