15
FOR LOOPS PROF. DAVID ROSSITER 1/15 1/15

01 For Loops.pdf

Embed Size (px)

Citation preview

Page 1: 01 For Loops.pdf

FOR LOOPSPROF. DAVID ROSSITER

1/151/15

Page 2: 01 For Loops.pdf

AFTER THIS PRESENTATIONYou'll be able to create differentkinds of for loop

2/152/15

Page 3: 01 For Loops.pdf

WE WILL LOOK ATfor

for ... in

for ... of

3/153/15

Page 4: 01 For Loops.pdf

FOR LOOPS for clearly shows the start and end values

for is especially good for handling a series of data

( data_structure.length tells you how many items data_structure contains )

4/154/15

Page 5: 01 For Loops.pdf

<html><head> <script> var continents=["Australia", "Africa", "Antarctica", "Eurasia", "America"]; var response, count=0; for (var index=0; index < continents.length; index++) response = confirm("Have you been to " + continents[index] + "?"); if (response) count++; alert("You have been to " + count + " continents!"); </script></head></html>

5/155/15

Page 6: 01 For Loops.pdf

6/156/15

Page 7: 01 For Loops.pdf

FOR ... IN LOOPSfor ... in gives you the index of each item

7/157/15

Page 8: 01 For Loops.pdf

<!doctype html><html><head> <script> var continents=["Australia", "Africa", "Antarctica", "Eurasia", "America"]; var response, count=0; for (var index in continents) response=confirm("Have you been to " + continents[index] + "?"); if (response) count++; alert("You have been to " + count + " continents!"); </script></head></html>

8/158/15

Page 9: 01 For Loops.pdf

FOR ... IN LOOPSThis example shows how for ... in can be used to access the content of a data structure

9/159/15

Page 10: 01 For Loops.pdf

<!doctype html><html><head> <title>Example of for in</title> <script> var response, count=0; var onePerson = initials:"DR", age:40, job:"Professor" ;

for (var property in onePerson) alert(property + "=" + onePerson[property]); </script></head></html>

10/1510/15

Page 11: 01 For Loops.pdf

11/1511/15

Page 12: 01 For Loops.pdf

FOR ... OF LOOPSfor ... of gives you each item

12/1512/15

Page 13: 01 For Loops.pdf

<!doctype html><html><head> <title>Example of for of</title> <script> var continents=["Australia", "Africa", "Antarctica", "Eurasia", "America"]; var response, count=0; for (var continent of continents) response = confirm("Have you been to " + continent + "?"); if (response) count++; alert("You have been to " + count + " continents!"); </script></head></html>

13/1513/15

Page 14: 01 For Loops.pdf

OMITTING PARTSThe 3 parts of the for can be omitted

E.g. this will make an infinite loop:

for ( ; ; ) alert("Welcome!");

14/1514/15

Page 15: 01 For Loops.pdf

This is OK:

var number=1; for ( ; number <= 12; number++ ) alert(number + " times 9 = ", number * 9);

So is this:

for (var rabbits=2, generation=1; generation<=12; generation++, rabbits *= 2 ) alert("gen: " + generation + " total:" + rabbits);

15/1515/15