1 javascript loops n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
1. JavaScript Loops PowerPoint Presentation
Download Presentation
1. JavaScript Loops

Loading in 2 Seconds...

play fullscreen
1 / 34

1. JavaScript Loops - PowerPoint PPT Presentation


  • 82 Views
  • Uploaded on

1. JavaScript Loops. Repeating Code. A loop statement is a control structure that repeatedly executes a statement or a series of statements while a specific condition is true or until a specific condition becomes true. There are four types of loop statements: for statements while statements

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about '1. JavaScript Loops' - lassie


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
repeating code
Repeating Code
  • A loop statement is a control structure that repeatedly executes a statement or a series of statements while a specific condition is true or until a specific condition becomes true.
  • There are four types of loop statements:
    • for statements
    • while statements
    • do...while statements
    • for in statements (only for arrays)
for loop
For Loop
  • Used for repeating a statement or a series of statements as long as a given conditional expression evaluates to true
  • Each repetition of a looping statement is called an iteration
  • A counter is a variable that increments or decrements with each iteration of a loop statement
  • “For” is particularly useful when you know how many times you want the loop to be run

for (initialization; condition; update statement) {

statements;

}

for explained
For Explained

Output:

0

1

2

3

4

for(var i = 0; i < 5; i ++){

document.write( i + "<br/>");

}

for expanded
For Expanded
  • It is not necessary to increment by +1
  • You could go up or down by any value.
  • Try the demo
while statement
While Statement
  • A while statement keeps repeating until its conditional expression evaluates to false.
  • We can use a counter if we like, but we don’t have to. For this reason, while loops are particularly useful when you don’t know the number of iterations ahead of time, for example, reading all the data in a file.

while (condition) {

statements

}

while example
While Example

var counter = 1;

while(counter < 5) {

document.write(counter + “<br/>”);

counter++;

}

Output:

1

2

3

4

infinite loop
Infinite Loop
  • In an infinite loop, a loop statement never ends because its conditional expression is never false. While loops are particularly susceptible to this, because there need not be a counter, but this can happen in any of the loops.
  • Ex. By never changing the value of the counter inside of a loop, this loop will never terminate.

var count = 1;

while (count <= 10) {

document.write(“The number is “ + count);

}

do while syntax
do…while Syntax

do...while statements always execute once, before a conditional expression is evaluated

You don’t see this loop very often, but one place where it is very useful is in forcing users to provide valid data in a popup.

do {

//statements

} while(condition)

do while example
do…while Example

do {

varluckyNumber = prompt('What is your lucky number?','');

luckyNumber = parseInt(luckyNumber);

} while (isNaN(luckyNumber));

The user will be prompted until they give you a valid number!

arrays
Arrays
  • We learned about Numbers, Strings, Booleans,
  • But what about when we want to store lists of Numbers, Strings or Booleans
  • We could define a whole set of variables but when we have 100’s of numbers we need a better way
what is an array
What is an Array?
  • Holds a list of data
  • Each piece of data can be accessed using it’s numerical index
  • Basically a group of variables that all have the same name, and are accessed by a numeric value
  • Arrays start at element 0; the last element is

array.length -1

what is an array cont
What is an Array? (cont…)
  • Imagine I have a rack of shoes, and I give each shoe a number.
  • Then I can access the shoes by their number
arrays cont
Arrays (cont)

Element: Each slot in an array (values in the table)

Index: The reference to each slot in the array. (numeric position)

First element is 0

Second is 1

Third is 2

declaring an array
Declaring an Array

<script type="text/javascript">

varshoeRack = new Array();

shoeRack[0] = "Tennis Shoes";

shoeRack[1] = "Running Shoes";

shoeRack[2] = "Red Heels";

shoeRack[3] = "Black Flats";

shoeRack[4] = "Climbing Shoes";

shoeRack[5] = "Rain Boots";

</script>

<script type="text/javascript">

varshoeRack = ["Tennis Shoes", "Running Shoes", "Red Heels"];

</script>

accessing elements
Accessing elements

We can retrieve elements in arrays by their indexes:

alert(shoeRack[1]); //displays running shoes

array s can be of mixed types
Arrays can be ofMixed Types

<html>

<body>

<script type="text/javascript">

var mixed= new Array();

numArray[0] = 12

numArray[1] = “hello”

numArray[2] = “French”

numArray[3] = 18;

alert(numArray[2]); //displays French

</script>

</body>

</html>

getting the length of an array
Getting the length of an Array

<html>

<body>

<script type="text/javascript">

varshoeRack = new Array();

shoeRack[0] = "Tennis Shoes";

shoeRack[1] = "Running Shoes";

shoeRack[2] = "Red Heals";

shoeRack[3] = "Black Flats";

alert(“length of array is “ + shoeRack.length); //displays 4

</script>

</body>

</html>

arrays and for loops
Arrays and For Loops

<html>

<body>

<script type="text/javascript">

varshoeRack = new Array();

shoeRack[0] = "Tennis Shoes";

shoeRack[1] = "Running Shoes";

shoeRack[2] = "Red Heals";

shoeRack[3] = "Black Flats";

for(vari = 0; i < shoeRack.length; i++){

document.write(shoeRack[i] + "<br/>");

}

</script>

</body>

</html>

If you try to access an element beyond the length of the list, you will get an array out of bounds error. Remember – the index of the last element is the length of the array minus one.

arrays and the for i n loop
Arrays and the For In Loop
  • Simplifies the for loop to loop through arrays

for(variable in array) {

statement

}

  • The code within the { }’s is executed once for every object
  • [This one is not in your book, but you can read about it online at W3Schools.]
arrays and the for in loop
Arrays and the For In Loop

<html>

<body>

<script type="text/javascript">

varshoeRack = new Array();

shoeRack[0] = "Tennis Shoes";

shoeRack[1] = "Running Shoes";

shoeRack[2] = "Red Heals";

shoeRack[3] = "Black Flats";

for(vari in shoeRack){

document.write(shoeRack[i] + "<br/>");

}

</script>

</body>

</html>

associative arrays
Associative Arrays
  • Sometimes it doesn’t make sense to access information from it’s numeric index in a list.
  • Sometimes it’s easier to access elements by a string key.
  • Note the keys in associative arrays have to be Strings
associative array example
Associative Array Example

var capitols = new Array();

capitols[“Washington”] =“Olympia”;

capitols[“California”] = “Sacramento”;

capitols[“Texas”] = “Austin”;

capitols[“Flordia”] = “Tallahassee”;

//displays Olympia

alert(capitols[“Washington”]);

multi dimensional arrays
Multi-Dimensional Arrays
  • We can create an array of arrays that canbe represented by multi-column tables.
declaring 2 dimensional arrays
Declaring 2 Dimensional Arrays

<html>

<body>

<script type="text/javascript">

varusCities = new Array();

usCities[0] = ['Seattle', 'Olympia', 'Tahoma‘];

usCities[1] = ['San Fransico', 'LA', 'San Diego‘];

usCities[2] = ['Dallas', 'Austin', 'Houston', 'Desert’];

usCities[3] = ['Miami', 'Sarasota‘];

</script>

</body>

</html>

accessing 2 dimensional arrays
Accessing 2 dimensional Arrays

//will display Desert

document.write(usCities[2][3]);

  • The first number represents what sub array to access
  • The second number represents what element in the sub array to get
join example
Join (example)

vargroceryList = new Array();

groceryList[0] = 'Jam';

groceryList[1] = 'Peanut Butter';

groceryList[2] = 'Bread';

groceryList[3] = 'Syrup';

vargroceryString = groceryList.join('! ');

//now display the grocery list

document.write("grocery list: " + groceryString);

//output: ‘Jam! Peanut Butter! Bread! Syrup!

  • Merges the array into one string placing the token of your choice in between the array elements.
  • Token examples:
    • “,”
    • And
    • !
sort example
Sort (example)

vargroceryList = new Array();

groceryList[0] = 'Jam';

groceryList[1] = 'Peanut Butter';

groceryList[2] = 'Bread';

groceryList[3] = 'Syrup';

groceryList.sort();

for(i in groceryList) {

document.write(groceryList[i] + "<br />");

}

//we now have ‘bread, jam, peanut butter, syrup

p ush example
Push (example)

vargroceryList = new Array();

groceryList[0] = 'Jam';

groceryList[1] = 'Peanut Butter';

groceryList[2] = 'Bread';

groceryList[3] = 'Syrup';

groceryList.push('Pickel'); //adds pickel to the end of the array

Unshift will add an element to the front of the list, without overwriting.

p op example
Pop (example)

vargroceryList = new Array();

groceryList[0] = 'Jam';

groceryList[1] = 'Peanut Butter';

groceryList[2] = 'Bread';

groceryList[3] = 'Syrup';

$lastItem = groceryList.pop(); //lastItem is syrup

Takes the item off the end of the array. Reduces the size of the array by 1.

Shift will do the same thing, but remove from the front of the list.

c oncat example
Concat(example)

vartomsGroceryList = new Array();

tomsGroceryList[0] = 'Jam';

tomsGroceryList[1] = 'Peanut Butter';

tomsGroceryList[2] = 'Ham';

varbradsGroceryList = new Array();

bradsGroceryList[0] = 'Eggs';

bradsGroceryList[1] = 'Syrup';

vartomsAndBradsGroceries = tomsGroceryList.concat(bradsGroceryList);

//contains: Jam, Peanut Butter, Ham, Eggs, Syrup

Adds two arrays together. The second array is just added to the end of the first array