Scripting - PowerPoint PPT Presentation

1 / 70
About This Presentation
Title:

Scripting

Description:

All statements must end with semi-colons (;) Print Line Example HEAD TITLE Welcome /TITLE ... Semi-colon ( ;') Do not place after condition. Place after ... – PowerPoint PPT presentation

Number of Views:32
Avg rating:3.0/5.0
Slides: 71
Provided by: birgl
Category:

less

Transcript and Presenter's Notes

Title: Scripting


1
Scripting
2
JavaScript
  • JavaScript scripting language
  • Originally created by Netscape
  • Facilitates disciplined approach to designing
    computer programs
  • Enhances functionality and appearance of Web
    pages
  • Jscript
  • Microsofts version of JavaScript

3
JavaScript
  • ltSCRIPTgtlt/SCRIPTgt tag
  • Encloses entire script
  • Attribute LANGUAGEJavaScript
  • Indicates scripting language (JavaScript default
    in IE5 Netscape)
  • Tag must be closed at the end of the script
  • Correct method call syntax
  • object.method( string, additional arguments
    )

4
JavaScript
  • document.writeln( ltH1gtargumentlt/H1gt )
  • Case-sensitive, like all JavaScript functions
  • Uses the writeln method in the browsers document
    object
  • Prints the string, which can consist of any text
    and HTML tags
  • String must be surrounded by quotation marks
    ()
  • Statement terminators
  • All statements must end with semi-colons ()

5
Print Line Example
  • ltHEADgt
  • ltTITLEgtWelcomelt/TITLEgt
  • ltSCRIPT LANGUAGE"JavaScript"gt
  • document.writeln
  • ("lth2gtWelcome to Scriptinglt/h2gt")
  • lt/scriptgt
  • lt/HEADgt

6
Write and Writeln
  • Object document methods
  • writeln
  • Positions output cursor on next line when
    finished
  • write
  • Leaves the output cursor where it is when done
    executing
  • Both begin output where previous statement
    stopped
  • Line breaks inserted in two ways
  • document.writeln( Have altbrgtNice Day! )
  • document.writeln( Have a\nNice Day! )

7
Window.Alert
  • Methods in window object
  • Call on-screen windows
  • window.alert( argument )
  • Method calls alert window with window text
    "argument"
  • Outputs button with text and OK button
  • window.prompt()
  • Prompts user for string (discussed later)
  • Scripts restart when page reloaded/refreshed

8
Alert Example
  • ltHEADgt
  • ltTITLEgtWelcomelt/TITLEgt
  • ltSCRIPT LANGUAGE"JavaScript"gt
  • window.alert
  • ("Welcome to Scripting")
  • lt/scriptgt
  • lt/HEADgt

9
Common Escape Sequences
10
Variables
  • Location in memory where values are stored
  • Variable name can be any valid identifier
  • Identifier series of characters
  • Letters, digits, underscores (_) and dollar
    signs ()
  • Cannot begin with a digit
  • Valid identifiers Welcome, value, _value,
    m_inputField1, C3PO and R2D2
  • Invalid identifiers 7button, Say\Hello and
    field5
  • Identifiers are case-sensitive

11
Variables
  • Variable name convention
  • Begin with lowercase first letter
  • Every following word has first letter capitalized
  • goRedSox, bostonUniversityRules
  • Declarations
  • var name1, name2
  • Indicate that name1 and name2 are program
    variables

12
Variables
  • Method window.prompt( arg1, arg2 )
  • Calls window that allows user to enter value to
    use in the script
  • arg1 text that will appear in window
  • arg2 text that will initially appear in input
    line
  • firstNumber window.prompt()
  • Assigns value entered by the user in prompt
    window to variable first
  • "" a binary operator
  • Assigns value of right operand to left operand

13
Variables
  • Good programmers write many comments
  • Helps other programmers decode script
  • Aids debugging
  • Comment Syntax
  • One-line comment // text
  • Multi-line comment / text /
  • parseInt()
  • Function accepts a string and returns an integer
    value
  • Not a method because we do not refer to an object
    name
  • number1 parseInt( firstNumber )
  • Operates right-to-left (due to the "" sign)

14
Variables
  • sum number1 number2
  • Adds number1 and number2
  • Assigns result to variable sum
  • String concatenation
  • Combines string and another data type
  • Other data type can be another string
  • Example
  • If age 20,
  • document.writeln( I am age years old! )
  • Prints I am 20 years old!

15
Adding 2 Numbers Example
  • ltscript languageJavaScript"gt
  • / Multiple line comments
  • can be written /
  • var numinput1, numinput2, number1, number2, sum
  • numinput1 window.prompt ("Enter number 1",
    "0")
  • numinput2 window.prompt ("Enter number 2",
    "0")
  • // Single line comment
  • // Functions are case sensitive
  • number1 parseInt( numinput1 )
  • number2 parseInt( numinput2 )
  • sum number1 number2
  • document.write ("Total is " sum)
  • lt/scriptgt

16
Adding 2 Numbers Example
  • Inputs
  • Output

17
Memory Concepts
  • Variables
  • Name corresponds to location in memory
  • Have 3 attributes
  • Name
  • Type
  • Value
  • Memory
  • When a value assigned to a variable, it
    overwrites any previous value
  • Reading values is non-destructive
  • sum number1 number2
  • Does not change number1 or number2

18
Arithmetic
  • Binary Operators
  • Used in arithmetic operations
  • Modulus operator ()
  • Yields remainder after division
  • Examples
  • 43 5 3
  • 8.7 3.4 1.9
  • 24 6 0

19
Arithmetic
20
Arithmetic
  • Arithmetic operations
  • Operate right to left (like the sign)
  • Rules of operator precedence
  • Operations execute in a specific order

21
Order of Precedence
22
Decision Making
  • if structure
  • Program makes decision based on truth or falsity
    of condition
  • If condition met (true)
  • Statement(s) in body of structure executed
  • If condition not met (false)
  • Statement(s) in body of structure skipped
  • Format
  • if (condition)
  • statement
  • (additional statements)
  • Semi-colon ()
  • Do not place after condition
  • Place after every statement in body of structure

23
Operators
24
If Structure
  • Pseudocode
  • If students grade is greater than or equal to 60
  • Print Passed
  • JavaScript statement
  • if( grade gt 60 )
  • document.writeln( Passed )
  • Proper syntax indent all lines within structure

25
If Structure
  • Conditions which evaluate to true
  • True condition
  • Non-zero numeric value
  • String containing at least one character
  • Conditions which evaluate to false
  • False condition
  • Numeric value 0
  • Empty string
  • Variable with no assigned value

26
Comparison Example
  • ltscript languageJavaScript"gt
  • var numinput1, numinput2, number1, number2, sum
  • numinput1 window.prompt ("Enter number 1",
    "0")
  • numinput2 window.prompt ("Enter number 2",
    "0")
  • number1 parseInt( numinput1 )
  • number2 parseInt( numinput2 )
  • document.writeln("First number is " number1
    "ltbrgt")
  • document.writeln("Second number is " number2
    "ltbrgtltbrgt")

27
Comparison Example
  • if ( number1 number2 )
  • document.writeln(number1 " is equal to "
    number2 "ltbrgt")
  • if (number1 ! number2)
  • document.writeln(number1 " is not equal to "
    number2 "ltbrgt")
  • if (number1 lt number2)
  • document.writeln(number1 " is less than "
    number2 "ltbrgt")
  • if (number1 lt number2)
  • document.writeln(number1 " is less than or
    equal to " number2 "ltbrgt")

28
Comparison Example
  • if (number1 gt number2)
  • document.writeln(number1 " is greater than or
    equal to " number2 "ltbrgt")
  • if (number1 gt number2)
  • document.writeln(number1 " is greater than "
    number2 "ltbrgt")
  • lt/scriptgt

29
Comparison Example
  • First number is 100
  • Second number is 50
  • 100 is not equal to 50
  • 100 is greater than or equal to 50
  • 100 is greater than 50

30
Comparison Example
  • First number is 0
  • Second number is 00 is equal to 00 is less
    than or equal to 00 is greater than or equal to
    0

31
Comparison Example
  • If Cancel button is pressed for window prompt
  • First number is NaN
  • Second number is NaNNaN is not equal to NaN

32
Control Structures
  • 3 Types of selection structures
  • if
  • Single-selection structure
  • Selects or ignores a single action or group of
    actions
  • if/else
  • Double-selection structure
  • Selects between two actions or groups of actions
  • switch
  • Multiple-selection structure
  • Selects among many actions or groups of actions

33
Control Structures
  • Four types of repetition structures
  • while
  • do/while
  • for
  • for/in
  • Two ways to combine structures
  • Control-structure stacking
  • Single-entry/single-exit structures
  • Control-structure nesting

34
Control Structures
  • All control structure names are keywords
  • Reserved by language for feature implementation
  • May not be used as variable names

35
If-Else Structure
  • Pseudocode
  • If students grade is greater than or equal to 60
  • Print Passed
  • else
  • Print Failed
  • JavaScript statement
  • if ( grade gt 60 )
  • document.writeln( Passed )
  • else
  • document.writeln( Failed )

36
? Structure
  • Conditional Operator (?)
  • JavaScripts only ternary operator
  • Takes three operands
  • 1. Boolean expression
  • 2. Value for conditional expression if true
  • 3. Value for conditional expression if false
  • Example
  • document.writeln(
  • studentGrade gt 60 ? Passed Failed )
  • Same operation as preceding if/else statement

37
Nested If-Else Structure
  • Pseudocode
  • If students grade is greater than or equal to 90
  • Print A
  • else
  • If Students grade is greater than or equal to
    80
  • Print B
  • else
  • If students grade is greater than or equal to
    70
  • Print C
  • else
  • If students grade is greater than or equal to
    60
  • Print D
  • else
  • Print F

38
Nested If-Else Structure
  • JavaScript statement
  • if ( studentGrade gt 90 )
  • document.writeln( A )
  • else
  • if ( studentGrade gt 80 )
  • document.writeln( B )
  • else
  • if ( studentGrade gt 70 )
  • document.writeln( C )
  • else
  • if ( studentGrade gt 60 )
  • document.writeln( D )
  • else
  • document.writeln( F )

39
Nested If-Else Structure
  • Identical JavaScript statement
  • if ( studentGrade gt 90 )
  • document.writeln( A )
  • else if ( studentGrade gt 80 )
  • document.writeln( B )
  • else if ( studentGrade gt 70 )
  • document.writeln( C )
  • else if ( studentGrade gt 60 )
  • document.writeln( D )
  • else
  • document.writeln( F )
  • This form preferred by many because avoids deep
    indent

40
Dangling Else
  • JavaScript interpreter
  • Associates else statement with previous if
    statement unless indicated otherwise by braces
    ()
  • Example
  • if ( x gt 5 )
  • if ( y gt 5 )
  • document.writeln( x and y are gt 5 )
  • else
  • document.writeln( x is lt 5 )

41
Dangling Else
  • Because of indent, appears that else statement
    applies to first if statement
  • JavaScript interpreter really reads as
  • if ( x gt 5 )
  • if ( y gt 5 )
  • document.writeln( x and y are gt 5 )
  • else
  • document.writeln( x is lt 5 )

42
Dangling Else
  • To have JavaScript interpreter read structure as
    you intended, utilize braces ()
  • if ( x gt 5 )
  • if ( y gt 5 )
  • document.writeln( x and y are gt 5 )
  • else
  • document.writeln( x is lt 5 )
  • else statement now applies to first if statement

43
Compound Statement
  • Statement contained inside braces ( and )
  • Does not end with a semi-colon
  • All statements inside should end with semi-colons
  • if ( grade gt 60 )
  • document.writeln( Passed )
  • else
  • document.writeln( FailedltBRgt )
  • document.writeln( You must take the course
    again. )
  • JavaScript interpreter executes both writeln
    statements inside braces if the if condition is
    false
  • Without braces, last writeln statement outside
    if/else structure and will always execute

44
Counter Controlled Repetition
  • Uses a while repetition structure
  • Tests if variable counter has reached the target
    value using relative condition
  • counter incremented or decremented a set amount
    every loop
  • Structure concludes when condition becomes false
    (i.e. counter reaches target value)
  • Used
  • With or without user input
  • When there is a known number of loops

45
Average Example
  • ltscript language"javascript"gt
  • // Test for 10,10,20,20,30,30,40,40 Avg25
  • total 0
  • gradecount1
  • while (gradecount lt 8)
  • grade window.prompt ("Enter grade "
    gradecount " of 8","0")
  • total total parseInt(grade)
  • gradecount gradecount 1
  • average total / 8
  • document.writeln ("lth1gtAverage is
    "average"lt/h1gt")
  • lt/scriptgt

46
Sentinel Controlled Repetition
  • Uses a while repetition structure
  • Tests if variable counter has been set to
    sentinel value using equality condition
  • When user inputs string equal to sentinel value,
    condition will be false next time tested
  • Used when
  • User is input is incorporated into structure
  • Final number of loops unknown indefinite
    repetition
  • First user input should occur before while
    structure begins
  • Be sure to account for possibility of user
    initially entering sentinel value
  • Sentinel value chosen so not confused with an
    acceptable input value
  • -1 is a common sentinel value

47
Average Example-2
  • ltSCRIPT LANGUAGE "JavaScript"gt
  • var gradeCounter, gradeValue, total, average,
    grade
  • total 0
  • gradeCounter 0
  • grade window.prompt(
  • "Enter Integer Grade, -1 to Quit", "0" )
  • gradeValue parseInt( grade )
  • while ( gradeValue ! -1 )
  • total total gradeValue
  • gradeCounter gradeCounter 1
  • grade window.prompt(
  • "Enter Integer Grade, -1 to Quit", "0" )
  • gradeValue parseInt( grade )
  • if ( gradeCounter ! 0 )
  • average total / gradeCounter
  • document.writeln(
  • "ltH1gtClass average is " average "lt/H1gt" )

48
Assignment Operators
  • Assignment operations with identical results can
    be written different ways
  • Example 1
  • c c 3
  • Example 2
  • c 3
  • Both ways add 3 to the value of c
  • Example 2 executes faster
  • Small difference for individual operations
  • Significant over large number of operations

49
Assignment Operators
50
Increment/Decrement Operators
  • Increment operator ()
  • Example
  • c is identical to c 1 is identical to c
    c 1
  • Decrement operator (--)
  • Example
  • c-- is identical to c - 1 is identical to c
    c - 1
  • Faster operation
  • Save time over many repetitions
  • Can be preincremented/decremented or
    postincremented/decremented
  • Only makes a difference when variable appears in
    context of larger expression

51
Increment/Decrement Operators
52
For Repetition Structure
  • for repetition structure
  • Handles all details of counter-controlled
    repetition
  • JavaScript statement
  • for ( var i 1 i lt 7 i )
  • document.writeln( ltPgtltFONT SIZE i gtHTML
    Font size i lt/FONTgt )

53
For Repetition Structure
  • Optionals
  • If loopContinuationTest omitted JavaScript
    assumes condition is true (infinite loop)
  • Can omit initialization expression if variable
    initialized elsewhere in program
  • Can omit increment statement if incrementation
    occurs inside structure
  • If loop-continuation condition initially false,
    body of for structure not executed

54
Equivalent Structures
  • for structure
  • for ( initialization loopContinuationTest
    increment )
  • statement
  • while structure
  • initialization
  • while ( loopContinuationTest )
  • statement
  • increment

55
For Structure
  • Different methods for varying control variable in
    for structure
  • Examples
  • Control variable 1 to 100, increments of 1
  • for ( var i 1 i lt 100 i )
  • Control variable 100 to 1, increments of 1
    (decrements of 1)
  • for ( var i 100 i gt 1 --i )
  • Control variable 7 to 77 , steps of 7
  • for ( var i 7 i lt 77 i 7 )
  • Control variable over sequence of values 99, 88,
    77, 66, 55, 44, 33, 22, 11, 0
  • for ( var k 99 k gt 0 k - 11 )

56
Switch Structure
  • switch control structure
  • Contains multiple substructures
  • Actions executed depend on variable value
  • Works well classifying user inputs
  • break statement
  • Skips to end of switch structure
  • Should be at the end of every case sub-structure
  • If left out, JavaScript will continue to test
    user input against cases
  • default case
  • Is executed if variable did not match any of the
    cases

57
Switch Structure
  • JavaScript statement
  • var choice
  • choice window.prompt()
  • switch ( choice )
  • case a
  • actions
  • case b
  • actions
  • case z
  • actions
  • default
  • actions

58
Switch Example
  • ltscript language"javascript"gt
  • var starttag, endtag, listtype, validinput
    true
  • choice window.prompt ("Select list style\n"
  • "1 (bullet), 2 (numbered), 3 (lettered)","1")
  • switch (choice)
  • case "1"
  • starttag "ltulgt"
  • endtag "lt/ulgt"
  • listtype "lth1gtBullet Listlt/h1gt"
  • break
  • case "2"
  • starttag "ltolgt"
  • endtag "lt/olgt"
  • listtype "lth1gtNumbered Listlt/h1gt"
  • break

59
Switch Example
  • case "3"
  • starttag "ltol type\"A\"gt"
  • endtag "lt/olgt"
  • listtype "lth1gtLettered Listlt/h1gt"
  • break
  • // No match
  • default
  • validinput false
  • if (validinputtrue)
  • document.writeln (listtype starttag)
  • for (i1 ilt3 i)
  • document.writeln ("ltligtList Item " i
    "lt/ligt")
  • else
  • document.writeln ("Invalid choice")

60
  • User Input 1

61
Do-While Structure
  • Similar to while control structure
  • Difference
  • while structure only executes if condition is
    initially true
  • JavaScript statement
  • while ( condition )
  • statement
  • do/while structure always executes at least once
  • JavaScript statement
  • do
  • statement
  • while ( condition )

62
Break and Continue
  • Alter flow of control
  • break
  • Exits structure
  • continue
  • Skips remaining statements in structure
    continues with next loop iteration
  • When used properly
  • Performs faster than the corresponding structured
    techniques

63
Labeled Break
  • break statement
  • Breaks out of immediately enclosing repetition
    control structure
  • To break out of nested structures
  • Use labeled break statements
  • Begins with a label (identifier followed by
    colon)
  • Enclose structures to be broken out of within
    braces ()
  • Called labeled compound statement
  • When executing break statement, follow format
  • break label

64
Labeled Continue
  • Use of labeled continue statement
  • Follows same syntax and rules
  • After execution, continues with next iteration of
    enclosing labeled repetition structure

65
Labeled Break Example
  • stop
  • for ( var row 1 row lt 10 row )
  • for ( var column 1 column lt 5 column )
  • if ( row 5 )
  • break stop
  • document.write( " " )
  • document.writeln( "ltBRgt" )
  • document.writeln( "This line should not print" )
  • document.writeln( "End of script" )

66
Labeled Break Example
67
Labeled Continue Example
  • nextRow
  • for ( var row 1 row lt 5 row )
  • document.writeln( "ltBRgt" )
  • for ( var column 1 column lt 10 column )
  • if ( column gt row )
  • continue nextRow
  • document.write( " " )

68
Labeled Continue Example
69
System Date and Time
  • var RightNow new Date()
  • document.write("Today's date is "
    RightNow.getMonth() "-"
  • RightNow.getDate() "-" RightNow.getYear())
  • document.write ("ltbrgtYou entered this Web Page at
    exactly " RightNow.getHours() "")
  • if (RightNow.getMinutes()lt 10)
  • document.write("0" RightNow.getMinutes())
  • else
  • document.write(RightNow.getMinutes())
  • document.write("" RightNow.getSeconds())

70
Status and Navigator
  • window.status "Welcome to My Site"
  • var an navigator.appName
  • var av navigator.appVersion
  • var acn navigator.appCodeName
  • var ua navigator.userAgent
  • var hst location.host
  • var hstn location.hostname
  • document.write("You are using ltBgt" an "lt/Bgt,
    version " av ".ltBRgtIts code name is " acn
    ", and sends the header " ua "." )
  • document.write("ltbrgtThe name of this location is
    ltBgt" hst "lt/Bgt." )
  • document.write("ltbrgtThe name of this location is
    ltBgt" hstn "lt/Bgt." )
Write a Comment
User Comments (0)
About PowerShow.com