XP Tutorial 3 New Perspectives on JavaScript, Comprehensive1 Working with Arrays, Loops, and...
-
Upload
naomi-carr -
Category
Documents
-
view
216 -
download
0
description
Transcript of XP Tutorial 3 New Perspectives on JavaScript, Comprehensive1 Working with Arrays, Loops, and...
Tutorial 3 New Perspectives on JavaScript, Comprehensive 1
XP
Tutorial 3
Working with Arrays, Loops, and Conditional Statements
Creating a Monthly Calendar
Tutorial 3 New Perspectives on JavaScript, Comprehensive 2
XPObjectives
• Create an array• Populate and reference values from an array• Work with array methods
Tutorial 3 New Perspectives on JavaScript, Comprehensive 3
XPObjectives
• Work with For loops• Work with While loops• Loop through the contents of an array• Work with If, If... Else, and multiple
conditional statements
Tutorial 3 New Perspectives on JavaScript, Comprehensive 4
XPObjectives
• Use arrays, loops, and conditional statements to create a table
• Work with break, continue, and label commands
Tutorial 3 New Perspectives on JavaScript, Comprehensive 5
XPIntroducing the Monthly Calendar
• Program requirements– Easily usable on other Web pages– JavaScript code for calendar should be placed in
an external file named calendar.js– calendar.js should be run from a single function– Accessing and displaying monthly calendar table
should require minimal amount of recoding
Tutorial 3 New Perspectives on JavaScript, Comprehensive 6
XPCreating and Formatting the Monthly Calendar
Tutorial 3 New Perspectives on JavaScript, Comprehensive 7
XPThe Calendar Style Sheet
• Classes or id names to be created– Calendar is set in a table with id calendar_table– Cell containing calendar title has id
calendar_head– Seven cells containing days of week abbreviations
belong to class calendar_weekdays– Cells containing dates of month belong to class
calendar_dates– Cell containing current date has id
calendar_today
Tutorial 3 New Perspectives on JavaScript, Comprehensive 8
XPThe Contents of the calendar.css Style Sheet
Tutorial 3 New Perspectives on JavaScript, Comprehensive 9
XPThe calendar() Function
• Initial code for the calendar() functionfunction calendar() {
document.write("<table id='calendar_table'>");
document.write("</table>");}
Tutorial 3 New Perspectives on JavaScript, Comprehensive 10
XPThe calendar() Function
• Main tasks when creating calendar table– Creating the table header row– Creating the table row containing the names of the
days of the week– Creating the rows containing the days of the
month
Tutorial 3 New Perspectives on JavaScript, Comprehensive 11
XPWorking with Arrays
• Array – Collection of data values organized under a single
name– Each data value has a number or index – General form
array[I]
Tutorial 3 New Perspectives on JavaScript, Comprehensive 12
XPCreating and Populating an Array
• To create an arrayvar array = new Array(length);
• Arrays without a defined length can take up more memory
• Creating and populating an arrayvar array = new Array(values);
• Array literalvar array = [values];
Tutorial 3 New Perspectives on JavaScript, Comprehensive 13
XP Creating the monthName Array
Tutorial 3 New Perspectives on JavaScript, Comprehensive 14
XPThe Completed writeCalTitle() Function
Tutorial 3 New Perspectives on JavaScript, Comprehensive 15
XPWorking with Array Length
• JavaScript arrays – Not required to stay at a fixed size– Definition of a value not required for every item
• Sparse arrays– Arrays with several missing or null items
Tutorial 3 New Perspectives on JavaScript, Comprehensive 16
XPReversing an Array
• Arrays – Associated with a collection of methods that allow
you to change their contents, order, and size– Syntax for applying methods
array.method()• Methods for changing order of array items
after array is created– reverse() and sort()
Tutorial 3 New Perspectives on JavaScript, Comprehensive 17
XPSorting an Array
• sort() method – Sorts array items in alphabetical order
• Compare function– Used to sort nontextual data correctly– Compares values of two adjacent items in the
array at a time• Applying compare function to sort() method
array.sort(function)
Tutorial 3 New Perspectives on JavaScript, Comprehensive 18
XPExtracting and Inserting Array Items
• Subarray– A section of an array
• slice() method– Extracts a part of an array– Syntax: array.slice(start, stop)– Can be used to insert new items into an array
array.splice(start, size, values)
Tutorial 3 New Perspectives on JavaScript, Comprehensive 19
XPExtracting and Inserting Array Items
• Most efficient methods to insert or remove items– push()– pop()– unshift() – shift()
Tutorial 3 New Perspectives on JavaScript, Comprehensive 20
XPArray Methods
Tutorial 3 New Perspectives on JavaScript, Comprehensive 21
XPWorking with Program Loops
• Program loop– Set of commands that executes repeatedly until a
stopping condition is met• The For loop
– Counter variable is used to track number of times a set of commands is run
– General structure for (start; continue; update) { commands
}
Tutorial 3 New Perspectives on JavaScript, Comprehensive 22
XPThe For Loop
• Can be nested inside another• Command block
– Collection of commands that is run each time through a loop
– Distinguished by opening and closing curly braces { }
Tutorial 3 New Perspectives on JavaScript, Comprehensive 23
XPCounter Values in the For loop
Tutorial 3 New Perspectives on JavaScript, Comprehensive 24
XPFor Loops and Arrays
• For loops – Used to cycle through different values contained
within an array– General structure for accessing each value in
array for (var i=0; i < array.length; i++) { commands involving array[i] }
Tutorial 3 New Perspectives on JavaScript, Comprehensive 25
XPCreating the writeDayNames() Function
Tutorial 3 New Perspectives on JavaScript, Comprehensive 26
XPThe While Loop
• A command block is run as long as a specific condition is met
• Condition does not depend on value of a counter variable
• General syntaxwhile (continue) {
commands}
Tutorial 3 New Perspectives on JavaScript, Comprehensive 27
XPThe Do/While Loop
• Test to determine whether to continue to loop is made after the command block is run
• Structuredo {
commands } while (continue);
Tutorial 3 New Perspectives on JavaScript, Comprehensive 28
XPWorking with Conditional Statements
• Conditional statement – Runs a command or command block only when
certain conditions are met• If statement
– Most common conditional statement
Tutorial 3 New Perspectives on JavaScript, Comprehensive 29
XPThe Initial daysInMonth()
Tutorial 3 New Perspectives on JavaScript, Comprehensive 30
XPCalculating Leap Years
Tutorial 3 New Perspectives on JavaScript, Comprehensive 31
XPThe If Statement
• Syntaxif (condition) { commands}
• Modulus operator – Returns the integer remainder after dividing one
integer by another
Tutorial 3 New Perspectives on JavaScript, Comprehensive 32
XPNesting If Statements
• General structureif (thisYear % 4 == 0) { if statement for century years}
Tutorial 3 New Perspectives on JavaScript, Comprehensive 33
XPThe Complete daysInMonth() Function
Tutorial 3 New Perspectives on JavaScript, Comprehensive 34
XPThe If...Else Statement
• General structureif (condition) { commands if true} else { commands if false}
Tutorial 3 New Perspectives on JavaScript, Comprehensive 35
XPUsing Multiple Else...If Statements
• General structureif (condition 1) { first command block}else if (condition 2) { second command block}else if (condition 3) { third command block}...else { default command block}
Tutorial 3 New Perspectives on JavaScript, Comprehensive 36
XPThe Switch Statement
• Syntaxswitch (expression) {
case label1: commands1 break;
case label2: commands2 break; case label3: commands3 break;... default: default commands}
Tutorial 3 New Perspectives on JavaScript, Comprehensive 37
XPCreating the calendar() Function
• Steps– Calculate day of week in which the month starts– Precede first day of month with blank table cells– Loop through days of the month
• Writing each date in a different table cell• Starting a new table row on each Sunday• Ending the table rows after each Saturday
– Highlight current date in calendar
Tutorial 3 New Perspectives on JavaScript, Comprehensive 38
XPBuilding the Monthly Calendar
Tutorial 3 New Perspectives on JavaScript, Comprehensive 39
XPSetting the First Day of the Month
Tutorial 3 New Perspectives on JavaScript, Comprehensive 40
XPPlacing the First Day of the Month
• Loop to create blank table cellsdocument.write("<tr>");for (var i=0; i < weekDay; i++) {
document.write("<td></td>");}
Tutorial 3 New Perspectives on JavaScript, Comprehensive 41
XPThe While loop for Adding the Calendar Days
Tutorial 3 New Perspectives on JavaScript, Comprehensive 42
XP The Final calendar() Function
Tutorial 3 New Perspectives on JavaScript, Comprehensive 43
XPManaging Program Loops and Conditional Statements
• Break command– Used to terminate any program loop or conditional
statement– Often used to exit a program loop– Syntax: break;
Tutorial 3 New Perspectives on JavaScript, Comprehensive 44
XPThe continue Command
• Stops processing commands in current iteration of loop and jumps to next iteration
• Examplevar total = 0;for (var i=0; i < data.length; i++) { if (data[i]==null) continue; // continue with the next iteration
total += data[i];}
Tutorial 3 New Perspectives on JavaScript, Comprehensive 45
XPStatement Labels
• Labels – Used to identify statements in your code– Often used with break and continue commands to
direct a program to a particular statement• Syntax:
label: statement• Some programmers
– Discourage use of break, continue, and label statements
Tutorial 3 New Perspectives on JavaScript, Comprehensive 46
XPTips for Arrays, Program Loops, andConditional Statements
• Save space in your program code by – Declaring and populating each array in a single
new Array() declaration• Use array methods like
– sort() and reverse() to quickly rearrange contents of arrays
• Use a For loop when – Your loop contains a counter variable
Tutorial 3 New Perspectives on JavaScript, Comprehensive 47
XPTips for Arrays, Program Loops, andConditional Statements
• Use While loop for – More general stopping conditions
• To simplify your code– Avoid nesting too many levels of If statements
• Use Switch statement for – Conditional statements that involve variables with
several different possible values
Tutorial 3 New Perspectives on JavaScript, Comprehensive 48
XPTips for Arrays, Program Loops, andConditional Statements
• Avoid using break and continue statements to – Cut off loops unless necessary– Instead
• Set break conditions in the conditional expression for a loop