Javascript: Iteration
ATLS 3020 - Digital Media 2 Week 4 - Day 1
Javascript: Iteration ATLS 3020 - Digital Media 2 Week 4 - Day 1 - - PowerPoint PPT Presentation
Javascript: Iteration ATLS 3020 - Digital Media 2 Week 4 - Day 1 Repeating Code Exercise: Have the user enter a number between 1 and 10. Print the string Hello that many times - Programmers are lazy - Never copy and paste code (there
ATLS 3020 - Digital Media 2 Week 4 - Day 1
for(initialization; condition; update) { // inside of for loop } // outside of for loop Javascript
Syntax is important! ALL for loops must come in this form:
for(initialization, condition, update) { //stuff }
There are always 3 parts to the condition Initialization var i=0
Condition i<10
10 Update i++
document.write("Start"); for(var i=0; i<3; i++) { alert(i); } document.write("End"); Javascript
var i i = 0 alert(i) Start End i++ i < 3 i = 1 alert(i) i++ i < 3 i = 2 alert(i) 2 i++ 1 i < 3
for(var i=0; i<5; i++) { document.write("Index: " + i + "<br/>"); } Javascript var colors = ["red", "blue", "green", "yellow"]; for(var i=0; i<4; i++) { document.write(colors[i] + "<br/>"); } Javascript for(var i=1; i<11; i+=2) { document.write("Index: " + i + "<br/>"); } Javascript
i++ i = i + 1 i+=2 i = i + 2
var colors = []; alert("Enter 5 Colors."); for(var i=0; i<5; i++) { colors.push(prompt("Enter a color")); } document.write(colors); Javascript
Print the numbers 0-4 Print the odd numbers between 1-10 Print the colors red, blue, green, yellow User enters 5 colors, print the array
while(condition) { // inside of while loop } // outside of while loop Javascript
Syntax is the same as a for loop ALL for loops must come in this form:
for(condition) { //stuff }
The condition must always be true The while loop will keep running until the condition is false True conditions while(true) var i = 1; while(i == 1) False conditions while(false) var i = 1; while(i == 0)
Keep asking user to enter a color until they enter “red”
var color; while(color != "red") { color = prompt("Enter a color"); } Javascript var i = 0; while(i < 5) { document.write("Index: " + i + "<br/>"); i++; } Javascript
Print the numbers 0-4 Keep asking user to enter a color until they enter “red” and “blue”
var color1, color2; while(color1 != "red" && color2 != "blue") { color1 = prompt("Enter a color"); color2 = prompt("Enter another color"); } Javascript
Keep asking user to enter a number less than 5 or greater than 10
var number; while(number < 5 || number > 10) { number = prompt("Enter a number"); } Javascript
Continue playing the card game War!
2.5 Play a round: (This step is the same as in Lab 3) Remove the first cards from both of the player’s decks. Compare the two cards together. Print each of the cards and print who won the round, then add the two cards to the winner’s deck. (If it is war, print that the players are going to war and add both cards to player 1’s deck).
cards
4.5 Play a round of the game (same as above).