Вы находитесь на странице: 1из 5

1/21/2014

Loops and switch | JavaScript Tutorial


Log in

JavaScript Tutorial
Home Tutorial JavaScript: from the Ground to Closures First Steps Operators and constructs
Comparison operators, if..else Functions: declarations and expressions Tutorial

JavaScript: from the Ground to Closures


JavaScript: from the Ground to Closures Javascript and related technologies First Steps
First Steps

Loops and switch


Ilya Kantor

1. The w h i l eand d o . . w h i l eloops 2. The f o rloop 3. Jumping out with b r e a k 4. Skipping with c o n t i n u e 5. Jumping over blocks with labels 6. The s w i t c hconstruct 1. Example 2. User-input example Loop constructs allow to repeat a block of code multiple times, while the given condition is true. JavaScript has three types of loops.

Like

Setup your environment Hello, World! Variables and statements Browser Developer's Tools User interaction: alert, prompt and confirm Operators and constructs
Operators and constructs Operators Comparison operators, if..else Loops and sw itch

The w h i l eand d o . . w h i l eloops


These loops check condition before/after every iteration: 1 2 3 4 5 6 7 w h i l e ( i < 1 0 ){ / /d os o m e t h i n g } d o{ / /s o m e t h i n g }w h i l e( i < 1 0 )

Functions: declarations and expressions Mastering data types Four scents of "this" Type detection Function arguments Static variables and methods Scopes and Closures Decorators

Document and Events Object Oriented Programming Timing Frames and windows Regular expressions in JavaScript Advanced and Extra stuff

The code inside curly braces will repeat while the condition (i < 1 0in the example) holds true. An endless loop looks like: w h i l e ( t r u e ){ / /d os o m e t h i n g } As with many other languages, you check for 0like this:
Run!

1 v a ri=3 2 w h i l e ( i ){ 3 a l e r t ( i ) 4 } The loop above will stop when i = = 0 , because 0is f a l s ein boolean context. Note that i -decrements i , but returns a value before decrement. Thats why alert starts with 3and ends with 1 .

Donate Donate to this project

The f o rloop
This loop looks like: f o r ( i = 0 ; i < 1 0 ; i + + ){ a l e r t ( i ) } The statement consists of three parts divided by semicolon and the body. Here is a description of the parts (generally same as in C, Java, PHP etc): i = 0- starter This executes at loop start. i < 1 0- loop condition The condition to check if loop is finished. It is checked after every execution of loop body. i + +- increment An action to perform after every iteration, but before the loop condition is checked. For the given example, the loop body is executed with istarting from 0to 9 . When i + +makes i = 1 0 , the loop is stopped by condition i < 1 0 .

http://javascript.info/tutorial/loops-and-switch

1/5

1/21/2014
It is a common practice to define a loop variable inside f o r : f o r ( v a ri = 0 ;i < 1 0 ;i + + ){. . .}

Loops and switch | JavaScript Tutorial

You can leave any part of f o rempty. For example, a simple infinite loop looks like: f o r ( ; ; ){ / /w i l lr e p e a te t e r n a l l y( i nt h e o r y ) }

Check out the page: tutorial/intro/source/loop.html . The task is to rewrite f o rloop into w h i l ewith same code behavior.

Open solution

Create a loop that keeps prompting for a number exceeding 100. When a user types in a number>100, the loops must stop. Pressing ESC or clicking Cancel must stop the loop also. Check how it should work here .

Open solution

Jumping out with b r e a k


Sometimes it is required to break out of the loop right now. This is what b r e a kstatement does. The following loop will exit from loop when ibecomes 6 . The execution will continue from right after the loop (marked with asterisk). 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 v a ri = 0 w h i l e ( t r u e ){ i + + / /i n c r e a s eib yo n e

i f( i > 5 )b r e a k
a l e r t ( i ) } / /( * )

Skipping with c o n t i n u e
The c o n t i n u eoperator allows to skip the rest of the block. For example, the following code ignores negative values:
Run!

1 v a ri=3 2 w h i l e ( i < 3 ){ 3 4 i + + 5 6 i f( i < 0 )c o n t i n u e 7 8 a l e r t ( i ) / /( * ) 9 } The code labelled with asterisk is never executed for negative i , thanks to c o n t i n u e .

Jumping over blocks with labels


Loop labels is something special in JavaScript. They are used to break/continue through several nested loops. A label is put before loop statement, and can be put on a separate line: 1 o u t e r : 2 f o r ( ; ; ){ 3 / /. . . 4 i n n e r :f o r ( ; ; ){ 5 / /. . .

http://javascript.info/tutorial/loops-and-switch

2/5

1/21/2014
6 } 7 }

Loops and switch | JavaScript Tutorial

One can use b r e a kl a b e land c o n t i n u el a b e lto jump through several loops. The following example demonstrates how to break through two loop levels.
Run!

0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1 1 2 1 3 1 4

o u t e r : f o r ( ; ; ){ f o r ( i = 0 ;i < 1 0 ;i + + ){ i f( i>3 )b r e a ko u t e r ; } / /t h ep a r to fc o d ea f t e ri n n e rl o o pi sn e v e re x e c u t e d , / /b e c a u s eb r e a kj u m p sr i g h tt oo u t e rl a b e l } a l e r t ( " i = " + i ) ;

You can use c o n t i n u ein exactly the same way. It will jump to next iteration of labelled loop. An interesting thing about labels is that you can attach them to blocks:
Run!

0 1 m y :{ 0 2 0 3 f o r ( ; ; ){ 0 4 f o r ( i = 0 ;i < 1 0 ;i + + ){ 0 5 i f( i > 4 )b r e a km y ; 0 6 } 0 7 } 0 8 0 9 s o m e _ c o d e ; 1 0 1 1 } 1 2 a l e r t ( " a f t e rm y " ) ; In the given example, b r e a kjumps over s o m e _ c o d e , to the end of the block labelled with m y . That looks like g o t o , but it is not, because you cant break outside loops, and you also cant break to a place of code before. JavaScript has no goto. Even in latest editions of the standard.

A number is prime if it has exactly two divisors: 1 and itself. Or, in other words, n > 1is prime if numbers 2 . . n 1all divide nwith a non-zero remainder. Create a code which outputs all primes less than 10. There should be 2,3,5,7. P.S. The code should also work if 100, 1000, any other value in place of 10.

Open hint 1 Open solution

The s w i t c hconstruct
Another useful construct in JavaScript is s w i t c h . It provides a short syntax for multiple equality tests. It looks like this: 1 s w i t c h ( x ){ 2 c a s e' v a l u e 1 ' : / /i f( x= = =' v a l u e 1 ' ) 3 . . . 4 c a s e' v a l u e 2 ' : / /i f( x= = =' v a l u e 2 ' ) 5 . . . 6 d e f a u l t : 7 / /d e f a u l tc o d e 8 } Switch operator checks the argument against each c a s eand executes the code below the match until it meets the b r e a koperator. If no case matches, it goes to optional default label.

Example
Lets see a working example.

http://javascript.info/tutorial/loops-and-switch

3/5

1/21/2014
Run!

Loops and switch | JavaScript Tutorial

0 1 v a rx=2 0 2 0 3 s w i t c h ( x ){ 0 4 c a s e1 : 0 5 a l e r t ( ' n e v e re x e c u t e s ' ) 0 6 0 7 c a s e2 : 0 8 a l e r t ( ' x= = =2 ' ) 0 9 1 0 c a s e3 : 1 1 a l e r t ( ' x= = =3 ' ) 1 2 } The example above outputs 2 and 3. Thats because it starts execution from c a s e 2and goes on. To stop the execution of a case, we need to add b r e a k :
Run!

0 1 v a rx=2 0 2 0 3 s w i t c h ( x ){ 0 4 c a s e1 : 0 5 a l e r t ( ' n e v e re x e c u t e s ' ) 0 6 b r e a k 0 7 0 8 c a s e2 : 0 9 a l e r t ( ' x= = =2 ' ) / /< -s t a r t 1 0 b r e a k / /s t o p ! 1 1 1 2 c a s e3 : 1 3 a l e r t ( ' x= = =3 ' ) 1 4 b r e a k 1 5 } In the example above, every c a s eis appended by b r e a k . That is a usual practice to ensure that only one case is executed.

User-input example
The next example is based on user-input.
Run!

0 1 v a ra r g=p r o m p t ( " E n t e ra r g ? " ) 0 2 s w i t c h ( a r g ){ 0 3 c a s e' 0 ' : 0 4 c a s e' 1 ' : 0 5 a l e r t ( ' O n eo rz e r o ' ) 0 6 0 7 c a s e' 2 ' : 0 8 a l e r t ( ' T w o ' ) 0 9 b r e a k 1 0 1 1 c a s e3 : 1 2 a l e r t ( ' N e v e rh a p p e n s ' ) 1 3 1 4 c a s ef a l s e : 1 5 a l e r t ( ' F a l s e ' ) 1 6 b r e a k 1 7 1 8 d e f a u l t : 1 9 a l e r t ( ' U n k n o w nv a l u e :' + a r g ) 2 0 } If you enter 0or 1it starts execution from the corresponding c a s e , executes the first alert, then the second one and stops at b r e a k . If you enter 2 ,s w i t c hgoes right to c a s e2 , skipping first alert. If you type in 3 ,s w i t c hgoes to default case. Thats because p r o m p treturns string ' 3 ' , not number. Switch uses = = =to check equality, so c a s e 3will not match. Thats also the reason why c a s ef a l s ealso never works in this example. It would work if a r g= = =f a l s e , but prompt returns either a string or n u l l . Comparison operators, if..else Functions: declarations and expressions

The content of this site is available under the terms of CC BY-NC-SA. Ilya Kantor, 2011.

"JavaScript is a registered trademark of Oracle corp. This site is not affiliated with Oracle corp.

http://javascript.info/tutorial/loops-and-switch

4/5

1/21/2014

Loops and switch | JavaScript Tutorial

http://javascript.info/tutorial/loops-and-switch

5/5

Вам также может понравиться