ÍøÂçѧԺ

w3pop.com :: ÍøÂçѧԺ :: JavaScript :: JS For Ñ­»·

»áÔ±µÇ½

ÕʺÅ

ÃÜÂë

»Ø´ð

¼ÇסÃÜÂë

Íü¼ÇÃÜÂë? ×¢²á

JavaScript
JSÊýѧ¶ÔÏó²Î¿¼
JS×Ö·û´®¶ÔÏó²Î¿¼
JSº¯Êý²Î¿¼
JSʼþ²Î¿¼
Javascript ³£ÓÃÕ..
FFºÍIEϵÄjs¼æÈÝ..
jQuery ¼òµ¥½éÉÜ
jQuery / ºËÐÄ / ..
jQuery / ºËÐÄ / ..
ÈçºÎʹÓÃJSÀ´ÅжÏ..
JavascriptÔÚIEºÍ..
3¸öjs×Ö·û±àÂ뺯Ê..
javascript ÖÐµÄ ..

JS For Ñ­»·


×÷Õß:w3pop.com ·­Òë/ÕûÀí:w3pop.com ·¢²¼:2007-04-28 ä¯ÀÀ:26129 :: ::

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ÖеÄÑ­»·ÓÃÀ´Öظ´Ö´ÐÐÖ¸¶¨´ÎÊýµÄ´úÂë»òµ±Ìõ¼þÎªÕæÊ±ÖØ¸´Ö´ÐС£


Examples
Àý ×Ó

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±êÌâ


JavaScript Loops
JS Ñ­»·

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ÖÐÓÐÁ½ÖÖÑ­»·£º

  • for - loops through a block of code a specified number of times
    for - ´ÎÊýÑ­»·
  • while - loops through a block of code while a specified condition is true
    while - Ìõ¼þÑ­»·

The for Loop
forÑ­»·

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) 
{
code to be executed

}

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>
<body>
<script type="text/javascript">

var i=0
for (i=0;i<=10;i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>

Result
£¨ÔËÐкóµÄ½á¹ûΪ£©

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10


The while loop
while loopÑ­»·Óï¾ä

The while loop will be explained in the next chapter.
while / loop  Ñ­»·Óï¾ä½«ÔÚÏÂÒ»ÕÂ×÷¾ßÌå½²½â¡£

ÆÀÂÛ (4) 1 All