html5-img
1 / 34

1. JavaScript Loops

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

lassie
Download Presentation

1. JavaScript Loops

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 1. JavaScript Loops

  2. 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)

  3. 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; }

  4. For Explained Output: 0 1 2 3 4 for(var i = 0; i < 5; i ++){ document.write( i + "<br/>"); }

  5. For Expanded • It is not necessary to increment by +1 • You could go up or down by any value. • Try the demo

  6. 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 }

  7. While Example var counter = 1; while(counter < 5) { document.write(counter + “<br/>”); counter++; } Output: 1 2 3 4

  8. 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); }

  9. 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)

  10. 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!

  11. 2. Javascript Arrays

  12. 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

  13. 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

  14. 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

  15. 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 …

  16. 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>

  17. Accessing elements We can retrieve elements in arrays by their indexes: alert(shoeRack[1]); //displays running shoes

  18. 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>

  19. 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>

  20. 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.

  21. 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.]

  22. 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>

  23. 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

  24. Associative Array Example var capitols = new Array(); capitols[“Washington”] =“Olympia”; capitols[“California”] = “Sacramento”; capitols[“Texas”] = “Austin”; capitols[“Flordia”] = “Tallahassee”; //displays Olympia alert(capitols[“Washington”]);

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

  26. 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>

  27. 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

  28. 3. Javascript Built-in Array Functions

  29. Array Functions

  30. 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 • !

  31. 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

  32. 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.

  33. 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.

  34. 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

More Related