cis 133 mashup javascript, jquery and xml chapter 3 building arrays and controlling flow

65
CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Upload: lynette-webster

Post on 20-Jan-2016

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

CIS 133Mashup Javascript, jQuery and XML

Chapter 3Building Arrays and Controlling Flow

Page 2: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

ObjectivesIn this chapter, you will:

Store data in arrays

Use while statements, do/while statements, and for statements to repeatedly execute code

Use continue statements to restart looping statements

Use if statements, if/else statements, and switch statements to make decisions

Nest one if statement in another

2

Page 3: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

FORM FIELD REFERENCES

3

Page 4: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Referencing form fields Two ways to reference form fields

◦ By form name◦ Using the document object

SYNTAX◦ document.formname.fieldname.value vs.

document.getElementById(“idname”).value

<form name=“myform” >

First name: <input type=“text” id=“firstname” name=“first” value = “” />

</form>

Page 5: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Referencing form fields by name

document.formname.fieldname.value◦ Notes:

◦ formname is the attribute in the form tag◦ fieldname is either the NAME attribute of the form field

HTML Example:

<form name=“myform” >

First name: <input type=“text” id=“firstname” name=“first” value = “” />

</form>

Script Example:var x = document.myform.first.value;window.alert(x);

Page 6: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Referencing form fields using document object

document.getElementById(“fieldID”).value◦ Notes:

◦ fieldID is ONLY the ID attribute value of the form field

HTML Example:

<form name=“myform” >

First name: <input type=“text” id=“firstname” name=“first” value = “” />

</form>

Script Example:var x = document.getElementById(“first”).value;window.alert(x);

Page 7: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

ArraysONE VARIABLE HOLDS MANY VALUES, LIKE A LIST

7

Page 8: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Arrays An Array is a Javascript Object

◦ It contains one or more items, called elements ◦ Each element can hold any type of data

◦ Numbers, strings, objects

An array can hold many values under a single name

Page 9: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Using the Array Object JavaScript represents arrays with the Array object

◦ Contains a special constructor named Array()

Constructor◦ Special function type used as the basis for creating reference variables

Syntaxvar arrayObj = new Array(number);

9

Page 10: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Can Create Arrays and assign values all at once

An array can be created in three ways

Regular:◦ var myToys = new Array();◦ myToys[0] = “Wii”;◦ myToys[1] = “iPad”;◦ myToys[2] = “iPos”;

• Regular Condensed:var myToys=new Array(“Wii”,“iPad",“iPod”);

• Brackets Literal:var myToys=[" Wii”,“iPad",“iPod "];

Page 11: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

11

Declaring and Initializing Arrays (cont’d.)

Element◦ Each piece of data contained in an array

Index◦ Element’s numeric position within the array◦ Array element numbering

◦ Starts with index number of zero (0)

Basic rule of thumb◦ Only declare number of array elements if exact number of elements the

array will store is known

Page 12: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Array Length Length is a property of the array object

◦ indicates the number of elements that it contains

Can change length of array by adding or removing elements to it

arrayObj.length

12

Page 13: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Modifying Arrays To reference an element, use its index number

◦ Example: to reference the 2nd element in the newsSections array

newsSections[1]

To add more items to an array, assign another value:◦ arrayObj[3] = value;

To remove items from an array, reduce the length:◦ arrayObj.length = value;

To modify an elementvar myToys=[" Wii”,“iPad",“iPod "];myToys[0] = “Gameboy”;

Page 14: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Declaring and Initializing Arrays (cont’d.)

Can create an array without any elements◦ Add new elements as necessary◦ Array size can change dynamically

var colors = [];

colors[2] = "yellow";

JavaScript values assigned to array elements◦ Can be different data types

14

Page 15: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Accessing Element Information

To access an element’s value:◦ Include brackets and element index

Examples:

15

var sec1Head = document.getElementById("section1");

var sec2Head = document.getElementById("section2");

var sec3Head = document.getElementById("section3");

sec1Head.innerHTML = newsSections[0]; // "world"

sec2Head.innerHTML = newsSections[1]; // "local"

sec3Head.innerHTML = newsSections[2]; // "opinion"

Page 16: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Array Methods and Properties

Many properties and methods

Length is a common property var myToys=[“Wii”,“iPad",“iPod "];

window.alert(myToys.length);

indexOf is a common method – tells index var myToys=[“Wii”,“iPad",“iPod "];myToys.indexOf(“iPad”);

Page 17: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Using Array Methods

Page 18: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

var fruits = ["Apple", "Orange", "Donkey"]alert(fruits[0]);alert(fruits[1]);alert(fruits[2]);

//how long is the array?alert(fruits.length);

// remove the donkey – its not a fruit!fruits.pop();alert(fruits.length);

// add a bananafruits.push(“banana”);alert(fruits.length);

//change the Orange to a Peachfruits[fruits.length-2] = “peach”;

Changing Arrays

Page 19: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Associative Array Index array uses numeric index to identify elements

Associative array uses text string index to identify elements

19

var item= []item[“isbn”] = 1234-3333-2222-4321;item[“Name”] = “javascript”item[“cost”] = 122.00

Length property will always be zero, because length only counts numeric indexes

Page 20: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Associative Array To retrieve elements in an index array

Use a for/in loop

20

var item= []item[“isbn”] = 1234-3333-2222-4321;item[“Name”] = “javascript”item[“cost”] = 122.00document.write(“first item is ” + item[“isbn”]

var item= []item[“isbn”] = 1234-3333-2222-4321;item[“Name”] = “javascript”item[“cost”] = 122.00for (var i in item){ document.write(“<br />item is ” + item[i];}

Page 21: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

You try it!1. Create an array named musicStyles with elements “Jazz”, “Blues”.

2. Append a value “Rock’n’Roll”

3. Replace the second value from end by “Classic”. The array should become “Jazz”,”Classic”,”Rock’n’Roll”. The code should work for any array length.

4. Extract the last value from the array (use the pop method) and use the window.alert() method to display it.

Page 22: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Referencing Default Collections of Elements

getElementsByTagName() method◦ Can reference web page element by looking up all elements of a certain type

in document and referencing one element in that collection◦ Resulting collection uses syntax similar to arrays

Example:

document.getElementsByTagName("li")[2]

22

Page 23: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

DecisionsFLOW OF CONTROL USING: IF, WHILE, DO WHILE, FOR, AND SWITCH COMMANDS

23

Page 24: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

24

Making Decisions Decision making or flow control

◦ Process of determining the order in which statements execute in a program

Decision-making statements or decision-making structures◦ Special types of JavaScript statements used for making decisions

Page 25: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Designing Program Flow

Flowcharts◦ A diagram that uses special symbols to display the flow of execution in a program◦ Handy to ensure program reaches a logical conclusion◦ Comprised of various symbols

Page 26: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Designing Program Flow

◦ Start and End symbols◦ Indicate the beginning and end of the program

◦ Arrows◦ Show flow of control

◦ Input/Output◦ Accept data or represent the results of computations

◦ Decision◦ Contain a yes/no question or a true/false test

◦ Connector◦ Entry point/hookup point

◦ Process◦ Show a statement; piece of logic

Start

Page 27: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Designing Program Flow for sweaters.html

Start

Display line 1

Declare variables for prices

Assign values to variables

Display line 2

Display line 3

Display line 4

End

Page 28: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Working with Program Loops

A program loop is a set of commands that is executed repeatedly until a stopping condition has been met

Four kinds of loops◦ While◦ Do While◦ For ◦ For loop

Requires a counter variable tracks the number of times a set of commands is run

The collection of commands that is run each time through a loop is collectively known as a command block

Page 29: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

while Statements while statement

◦ Repeats a statement or series of statements◦ As long as a given conditional expression evaluates to a truthy value

Syntaxwhile (expression) {

statements}

Iteration◦ Each repetition of a looping statement

29

Page 30: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

while Statements (cont’d.)

A WHILE statement runs as long as a specific condition is met

Counter◦ Variable incremented or decremented with each loop statement iteration

Examples:◦ while statement using an increment operator◦ while statement using a decrement operator◦ while statement using the *= assignment operator

30

Page 31: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

31

var count = 1;while (count <= 5) { document.write(count + "<br />"); count++;}document.write("<p>You have printed 5 numbers.</p>");

while Statements (cont’d.)

Result in browser:

Page 32: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

32

var count = 10;while (count > 0) { document.write(count + "<br />"); count--;}document.write("<p>We have liftoff.</p>");

while Statements (cont’d.)

Result in browser is ??:

Page 33: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

33

var count = 1;while (count <= 100) { document.write(count + "<br />"); count *= 2;}

while Statements (cont’d.)

Result in browser:

Page 34: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

while Statements (cont’d.)

Infinite loop◦ Loop statement that never ends

◦ Conditional expression: never false

◦ Example:

34

var count = 1;while (count <= 10) { window.alert("The number is " + count + ".");}

Page 35: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

while Statements (cont’d.)

Example:◦ assigning array element values to table cells:

35

function addColumnHeaders() { var i = 0; while (i < 7) { document.getElementsByTagName("th")[i].innerHTML = daysOfWeek[i]; i++; }}

Page 36: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

do/while Statements do/while statement

◦ Similar to the while loop except that the condition check happens at the end of the loop.

◦ Executes a statement or statements once◦ Then repeats the execution as long as a given conditional expression evaluates to a

truthy value

Syntax

36

do { statements;} while (expression);

Note the semicolon used at the end of the do...while loop

Page 37: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

do/while Statements (cont’d.)

Examples:

37

var count = 2;do { document.write("<p>The count is equal to " + count + ".</p>"); count++;} while (count < 2);

var count = 2;while (count < 2) { document.write("<p>The count is equal to " + count + ".</p>"); count++;}

Page 38: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

do/while Statements (cont’d.)

Example:◦ adding days of week with a do/while statement instead of a while statement

38

var i = 0;do { document.getElementsByTagName("th")[i].innerHTML = daysOfWeek[i]; i++;} while (i < 7);

Page 39: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

for Statements Most compact form of looping

Includes the following three important parts:◦ The loop initialization where we initialize our counter to a starting value. The initialization

statement is executed before the loop begins.◦ The test statement which will test if the given condition is true or not. If condition is true

then code given inside the loop will be executed otherwise loop will come out.◦ The iteration statement where you can increase or decrease your counter

Repeats a statement or series of statements◦ As long as a given conditional expression evaluates to a truthy value

Syntax

39

for (counter_declaration; condition; counter_operation) { statements}

Page 40: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

for Statements (cont’d.)

Steps when JavaScript interpreter encounters a for loop1. Counter variable declared and initialized2. for loop condition evaluated3. If condition evaluation in Step 2 returns truthy value:

◦ for loop statements execute, Step 4 occurs, and the process starts over again with Step 2

If condition evaluation in Step 2 returns falsy value:◦ for statement ends◦ Next statement following the for statement executes

4. Update statement in the for statement executed

40

Page 41: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

41

• For loops are often used to cycle through the different values contained within an array

• To loop through the contents of an array, use length property:

var brightestStars = ["Sirius", "Canopus", "Arcturus", "Rigel", "Vega"];for (var count = 0; count < brightestStars.length; count++) { document.write(brightestStars[count] + "<br />");}

Result in browser:

for Statements (cont’d.)

Page 42: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

for Statements (cont’d.)

for statement◦ More efficient than a while statement

Examples:

42

var count = 1;while (count < brightestStars.length) { document.write(count + "<br />"); count++;}

for (var count = 1; count < brightestStars.length; count++) { document.write(count + "<br />");}

Page 43: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

for Statements (cont’d.)

Example:◦ addColumnHeaders() function with a for statement instead of a do/while

statement

43

function addColumnHeaders() { for (var i = 0; i < 7; i++) { document.getElementsByTagName("th")[i].innerHTML = daysOfWeek[i]; }}

Page 44: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

“For In” Loop

This loop is used to loop through an object's properties or associative arrays.

SYNTAXfor (variablename in object){ statement or block to execute;}

In each iteration one property from object is assigned to variablename and this loop continues until all the properties of the object are exhausted.

var txt="";

var person={fname:"John",lname:"Doe",age:25};

for (var x in person)

{

txt=txt + person[x];

}alert(txt);

Page 45: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Labels to control flow A label can be used with break and continue to control the flow more precisely.

Labels are used to identify statements in JavaScript code so that you can reference those statements elsewhere in a program

◦ Note: Line breaks are not allowed between the continue or break statement and its label name

◦ There should not be any other statement in between a label name and associated loop.

Page 46: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Managing Program Loops and Conditional Statements

Syntax◦ label: statement◦ break label;◦ continue label;

Page 47: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Loop Control JavaScript provides you full control to handle your loops and switch statement

◦ may be a situation when you need to come out of a loop without reaching at its bottom◦ The break command terminates any program loop or conditional statement◦ The syntax for the break command is: break;

◦ may also be a situation when you want to skip a part of your code block and want to start next iteration of the look◦ The continue command stops processing the commands in the current iteration of the loop and

jumps to the next iterationcontinue;

Page 48: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

48

for (var count = 1; count <= 5; count++) { if (count === 3) { continue; } document.write("<p>" + count + "</p>");}

Result in browser:

Using continue Statements to Restart Execution (cont’d.)

Page 49: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

49

for (var count = 1; count <= 5; ++count) {if (count == 3)

break;document.write("<p>" + count + "</p>");

}

Using BREAK Statements to Exit Execution (cont’d.)

Page 50: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Making Decisions Decision making

◦ Process of determining the order in which statements execute in a program

Decision-making statements, decision-making structures, or conditional statements

◦ Used when you need to adopt one path out of the given two paths ◦ Conditional statements allow your program to make correct decisions and

perform right actions◦ Runs a command or command block only when certain circumstances are

met◦ JavaScript supports 2 kinds of conditional statements which are used to

perform different actions based on different conditions◦ if .. else◦ switch

50

Page 51: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

if Statements Used to execute specific programming code

◦ If conditional expression evaluation returns truthy value

Syntax

if (condition) {

statements

}

}After the if statement executes:◦ Any subsequent code executes normally

51

Page 52: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

if Statements (cont’d.) Use a command block to construct a decision-making structure containing multiple statements

Command block◦ Set of statements contained within a set of braces

52

Page 53: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Working with Conditional Statements– “if”..”else”

To test between two conditions, use the following construction:

if (condition)

{

commands if condition is true

}

else

{

commands if otherwise

}

JavaScript condition is evaluated.

If the resulting value is true, given statement(s) in the if block, are executed

If condition is false then given statement(s) in the else block, are executed

yes no

Page 54: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

if/else Statements Executes one action if the condition is true

◦ And a different action if the condition is false

54

• Syntax for an if . . . else statement

if (expression) { statements}else { statements}

Page 55: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

if/else Statements (cont’d.)

Example:

55

var today = "Tuesday"if (today === "Monday") { document.write("<p>Today is Monday</p>");}else { document.write("<p>Today is not Monday</p>");}

Page 56: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Nested if and if/else Statements

Nested decision-making structures◦ One decision-making statement contains another decision-making statement

Nested if statement◦ An if statement contained within an if statement or within an if/else

statement

Nested if/else statement◦ An if/else statement contained within an if statement or within an if/else statement

56

Page 57: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Nested if and if/else Statements (cont’d.)

Example:

57

var salesTotal = 75;if (salesTotal > 50) { if (salesTotal < 100) { document.write("<p>The sales total is between 50 and 100.</p>"); }}

Page 58: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Else if constructions Compact version of nested if/else statements

◦ combine an else statement with its nested if statement◦ requires fewer characters◦ easier to read

58

Page 59: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

else if constructions (cont'd.)

59

if (gameLocation[i] === "away") { paragraphs[1].innerHTML = "@ ";}else if (gameLocation[i] === "home") { paragraphs[1].innerHTML = "vs ";}

if (gameLocation[i] === "away") { paragraphs[1].innerHTML = "@ ";}else { if (gameLocation[i] === "home") { paragraphs[1].innerHTML = "vs "; }}

else if version

nested if/else version

Page 60: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

else if constructions (cont'd)

Used to create backward-compatible event listeners:

60

var submitButton = document.getElementById("button");if (submitButton.addEventListener) { submitButton.addEventListener("click", submitForm, false);}else if (submitButton.attachEvent) { submitButton.attachEvent("onclick", submitForm);}

Page 61: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

Creating a Switch Statement

You can use multiple if...else if statements to perform a multiway branch

Not the best solution, especially when all of the branches depend on the value of a single variable.

Page 62: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

switch Statements Controls program flow by executing a specific set of statements

◦ Dependent on an expression value

Compares expression value to value contained within a case label

case label◦ Represents a specific value◦ Contains one or more statements that execute:

◦ If case label value matches the switch statement’s expression value

62

• The switch statement is given an expression to evaluate and several different statements to execute based on the value of the expression

• The interpreter checks each case against the value of the expression until a match is found

• If nothing matches, a default condition will be used.

Page 63: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

switch Statements (cont’d.)

Syntax

63

switch (expression) { case label: statements; break;193 case label: statements; break; ... default: statements; break;}

Page 64: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

switch Statements (cont’d.)

default label◦ Executes when the value returned by the switch statement expression

does not match a case label

When a switch statement executes:◦ Value returned by the expression is compared to each case label

◦ In the order in which it is encountered

break statement◦ Ends execution of a switch statement◦ Should be final statement after each case label

64

Page 65: CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow

65

function city_location(americanCity) { switch (americanCity) { case "Boston": return "Massachusetts"; break; case "Chicago": return "Illinois"; break; case "Los Angeles": return "California"; break; case "Miami": return "Florida"; break; case "New York": return "New York"; break; default: return "United States"; break; }}document.write("<p>" + city_location("Boston") + "</p>");

switch Statements (cont’d.)