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

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Advertisements

Tonight’s JavaScript Topics 1 Conditional Statements: if and switch The Array Object Looping Statements: for, while and do-while.
Flow Control if, while, do-while Juan Marquez (03_flow_control.ppt)
Session 5 JavaScript/JScript: Control Structures II Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
Creating PHP Pages Chapter 7 PHP Decisions Making.
Objectives Using functions to organize PHP code
1 CS101 Introduction to Computing Lecture 23 Flow Control & Loops (Web Development Lecture 8)
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
14/11/11.  These words have special meanings in themselves  These should NOT be used as Identifiers.  For example:  Break, do, function, case, else,
Executes a statement or statements for a number of times – iteration. Syntax for(initialize; test; increment) { // statements to be executed } Initial.
Tutorial 12 Working with Arrays, Loops, and Conditional Statements
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Tutorial 4 Decision Making with Control Structures and Statements Section A - Decision Making JavaScript Tutorial 4 -Decision Making with Control.
JavaScript, Third Edition
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
Introduction to JavaScript for Python Programmers
TODAY’S LECTURE Review Chapter 2 Go over exercises.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Arrays and Control Structures CST 200 – JavaScript 2 –
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Conditional Statements While writing a program, there may be a situation when you need to adopt one path out of the given two paths. So you need to make.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Decision Making with Control Structures and Statements (non-audio version) © Dr. David.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
L OO P S While writing a program, there may be a situation when you need to perform some action over and over again. In such situation you would need.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
JavaScript, Fourth Edition
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Working with Loops, Conditional Statements, and Arrays.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
XP Tutorial 3 New Perspectives on JavaScript, Comprehensive1 Working with Arrays, Loops, and Conditional Statements Creating a Monthly Calendar.
JavaScript and Ajax (Control Structures) Week 4 Web site:
JavaScript, Sixth Edition
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - JavaScript: Control Structures II Outline 9.1 Introduction 9.2 Essentials of Counter-Controlled.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Learning Javascript From Mr Saem
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
REPETITION CONTROL STRUCTURE
Tutorial 12 Working with Arrays, Loops, and Conditional Statements
Statements (6 of 6) A statement causes an action to be performed by the program. It translates directly into one or more executable computer instructions.
JavaScript: Control Statements.
CHAPTER 4 CLIENT SIDE SCRIPTING PART 2 OF 3
JavaScript: Control Statements I
ITM 352 Flow-Control: Loops
Arrays, For loop While loop Do while loop
Introduction to JavaScript for Python Programmers
Control Structures Functions Decision making Loops
JavaScript Data Concepts
During the last lecture we had a discussion on Data Types, Variables & Operators
T. Jumana Abu Shmais – AOU - Riyadh
Objectives In this chapter, you will:
Chap 7. Advanced Control Statements in Java
CIS 136 Building Mobile Apps
Presentation transcript:

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

Objectives In 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

FORM FIELD REFERENCES 3

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 First name:

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: First name: Script Example: var x = document.myform.first.value; window.alert(x);

Referencing form fields using document object document.getElementById(“fieldID”).value ◦Notes: ◦fieldID is ONLY the ID attribute value of the form field HTML Example: First name: Script Example: var x = document.getElementById(“first”).value; window.alert(x);

Arrays ONE VARIABLE HOLDS MANY VALUES, LIKE A LIST 7

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

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 Syntax var arrayObj = new Array(number); 9

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 "];

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

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

Modifying Arrays To reference an element, use its index number ◦Example: to reference the 2 nd 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 element var myToys=[" Wii”,“iPad",“iPod "]; myToys[0] = “Gameboy”;

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

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"

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”);

Using Array Methods

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 banana fruits.push(“banana”); alert(fruits.length); //change the Orange to a Peach fruits[fruits.length-2] = “peach”; Changing Arrays

Associative Array Index array uses numeric index to identify elements Associative array uses text string index to identify elements 19 var item= [] item[“isbn”] = ; item[“Name”] = “javascript” item[“cost”] = Length property will always be zero, because length only counts numeric indexes

Associative Array To retrieve elements in an index array Use a for/in loop 20 var item= [] item[“isbn”] = ; item[“Name”] = “javascript” item[“cost”] = document.write(“first item is ” + item[“isbn”] var item= [] item[“isbn”] = ; item[“Name”] = “javascript” item[“cost”] = for (var i in item) { document.write(“ item is ” + item[i]; }

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.

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

Decisions FLOW OF CONTROL USING: IF, WHILE, DO WHILE, FOR, AND SWITCH COMMANDS 23

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

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

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

Designing Program Flow for sweaters.html Start Display line 1 Declare variables for prices Assign values to variables D isplay line 2 Display line 3 Display line 4 End

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

while Statements while statement ◦Repeats a statement or series of statements ◦As long as a given conditional expression evaluates to a truthy value Syntax while (expression) { statements } Iteration ◦Each repetition of a looping statement 29

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

31 var count = 1; while (count <= 5) { document.write(count + " "); count++; } document.write(" You have printed 5 numbers. "); while Statements (cont’d.) Result in browser:

32 var count = 10; while (count > 0) { document.write(count + " "); count--; } document.write(" We have liftoff. "); while Statements (cont’d.) Result in browser is ??:

33 var count = 1; while (count <= 100) { document.write(count + " "); count *= 2; } while Statements (cont’d.) Result in browser:

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

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++; }

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

do/while Statements (cont’d.) Examples: 37 var count = 2; do { document.write(" The count is equal to " + count + ". "); count++; } while (count < 2); var count = 2; while (count < 2) { document.write(" The count is equal to " + count + ". "); count++; }

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);

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 }

for Statements (cont’d.) Steps when JavaScript interpreter encounters a for loop 1. Counter variable declared and initialized 2. for loop condition evaluated 3. 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

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] + " "); } Result in browser: for Statements (cont’d.)

for statement ◦More efficient than a while statement Examples: 42 var count = 1; while (count < brightestStars.length) { document.write(count + " "); count++; } for (var count = 1; count < brightestStars.length; count++) { document.write(count + " "); }

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]; }

“For In” Loop This loop is used to loop through an object's properties or associative arrays. SYNTAX for (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);

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.

Managing Program Loops and Conditional Statements Syntax ◦ label: statement ◦ break label; ◦ continue label;

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 iteration continue;

48 for (var count = 1; count <= 5; count++) { if (count === 3) { continue; } document.write(" " + count + " "); } Result in browser: Using continue Statements to Restart Execution (cont’d.)

49 for (var count = 1; count <= 5; ++count) { if (count == 3) break; document.write(" " + count + " "); } Using BREAK Statements to Exit Execution (cont’d.)

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

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

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

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

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 }

if/else Statements (cont’d.) Example: 55 var today = "Tuesday" if (today === "Monday") { document.write(" Today is Monday "); } else { document.write(" Today is not Monday "); }

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

Nested if and if/else Statements (cont’d.) Example: 57 var salesTotal = 75; if (salesTotal > 50) { if (salesTotal < 100) { document.write(" The sales total is between 50 and 100. "); }

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

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

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

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.

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.

switch Statements (cont’d.) Syntax 63 switch (expression) { case label: statements; break; 193 case label: statements; break;... default: statements; break; }

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

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(" " + city_location("Boston") + " "); switch Statements (cont’d.)