Top Banner

of 58

jsFunctionArray

Apr 08, 2018

Download

Documents

Amirul Asyraf
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/7/2019 jsFunctionArray

    1/58

    1

    JavaScript: Functions and Arrays

    October 18, 2005

    Slides modified fromInternet & World Wide Web: How to Program. 2004 (3rd)edition. By Deitel, Deitel, and Goldberg. Published by

    Prentice Hall. ISBN 0-13-145091-3

  • 8/7/2019 jsFunctionArray

    2/58

    2

    Chapter 10 - JavaScript:

    FunctionsOutline

    10.1 Introduction10.2 Program Modules in JavaScript

    10.3 Programmer-Defined Functions

    10.4 Function Definitions

    10.5 Random-Number Generation

    10.6 Example: Game of Chance

    10.7 Another Example: Random Image Generator10.8 Scope Rules

    10.9 JavaScript Global Functions

    10.10 Recursion

    10.11 Recursion vs. Iteration

    10.12 Web Resources

  • 8/7/2019 jsFunctionArray

    3/58

    3

    Objectives

    In this tutorial, you will learn:

    To understand how to construct programs

    modularly from small pieces called

    functions. To be able to create new functions.

    To understand the mechanisms used to

    pass information between functions.

    To introduce simulation techniques that userandom-number generation.

    To understand how the visibility of

    identifiers is limited to specific regions of

    programs.

  • 8/7/2019 jsFunctionArray

    4/58

    4

    10.2 Program Modules in

    JavaScript Modules in JavaScript

    Functions

    Methods

    Belong to an object JavaScript includes many useful pre-

    defined methods

    Combine with programmer-defined methods to

    make a program

  • 8/7/2019 jsFunctionArray

    5/58

    5

    10.2 Program Modules in

    JavaScript

    Function calls

    Name

    Left parenthesis

    Arguments separated by commas

    Constants, variables or expressions

    Right parenthesis

    Examples:

    total += parseFloat( inputValue );

    total += parseFloat( s1 + s2 );

  • 8/7/2019 jsFunctionArray

    6/58

    6

    10.3 Programmer-Defined

    Functions Defining functions

    All variables declared in function are called

    local

    Do not exist outside current function Parameters

    Also local variables

    Promotes reusability

    Keep short

    Name clearly

  • 8/7/2019 jsFunctionArray

    7/58

    7

    10.4 Function Definitions

    Format of a function definition

    function function-name( parameter-list )

    {

    declarations and statements

    }

    Function name any valid identifier

    Parameter list names of variables that will receive

    arguments Must have same number as function call

    May be empty

    Declarations and statements

    Function body (block of code)

  • 8/7/2019 jsFunctionArray

    8/58

    8

    10.4 Function Definitions

    Returning control return statement

    Can return either nothing, or a value

    return expression;

    No return statement same as return;

    Not returning a value when expected is an

    error

  • 8/7/2019 jsFunctionArray

    9/58

    9

    10.4 Function Definitions

    Writing a function to square twonumbers

    for loop from 1 to 10

    Pass each number as argument to square return value of argument multiplied by

    itself

    Display result

  • 8/7/2019 jsFunctionArray

    10/58

    10

    1

    2

    10 A Programmer-Defined square Function

    11

    12

    13

    31

    32

    33

    34

    Variable y gets the value of variable x.

    The return statement passes the value ofy * y

    back to the calling function.

  • 8/7/2019 jsFunctionArray

    11/58

    11

    10.5 Random-Number

    Generation Random-number generation introduces

    element of chance Math.random

    var randomValue = Math.random(); Floating point value between 0 and 1

    Adjust range by scaling and shifting

    Math.floor

    Always round down

    Math.floor( 1 + Math.random() *

    6 )

  • 8/7/2019 jsFunctionArray

    12/58

    12

    1

    2

    4

    5

    6

    7

    8

    9

    10 Roll a Six-Sided Die 6000 Times

    11

    12

    13

  • 8/7/2019 jsFunctionArray

    13/58

    13

    RollDie.html

    (3 of 3)

    44 document.writeln( "" );

    46 document.writeln( "Face" +

    47 "Frequency" );

    48 document.writeln( "1" +

    49 frequency1 + "" );

    50 document.writeln( "2" + frequency2 +

    51 "" );

    52 document.writeln( "3" + frequency3 +

    53 "" );

    54 document.writeln( "4" + frequency4 +

    55 "" );

    56 document.writeln( "5" + frequency5 +

    57 "" );

    58 document.writeln( "6" + frequency6 +

    59 "" );

    60 // -->

    61

    62

    63

    64 65

    Click Refresh (or Reload) to run the script again

    66

    67

    The results of rolling the die

    600 times are displayed in a

    table.

  • 8/7/2019 jsFunctionArray

    14/58

    14

    10.7 Another Example:

    Random Image Generator Randomly selecting an image

    Images have integer names (i.e., 1.gif,2.gif, , 7.gif)

    Generate random number in proper range Update src property

  • 8/7/2019 jsFunctionArray

    15/58

    15

    RandomPicture.html

    (1 of 1)

    1

    2

    4

    5

    6

    7

    8

    9

    10 Random Image Generator

    11

    12

    13

    18

    19

    20

    21

    22

    23

    Click Refresh (or Reload) to run the script again

    24

    25

    Inserting a random number into the images src

    property with document.write and Math.random

  • 8/7/2019 jsFunctionArray

    16/58

    16

    10.8 Scope Rules

    Scope Portion of program where identifier can be

    referenced

    Inside function is local or function scope Identifiers exist only between opening and

    closing braces

    Local variables hide global variables

  • 8/7/2019 jsFunctionArray

    17/58

    17

    10.8 Scope Rules

    Scope demonstration Global variable x initialized to 1

    start has local variable x initialized to 5

    functionA has local variable x initialized to25

    functionB has no local variable x

    Observe output of each function

    A Scoping Example< title>

  • 8/7/2019 jsFunctionArray

    18/58

    18

    11

    12

    13

    52

    53

    54

    55

    56

    Function functionBmultiplies the value

    ofx by 10.

    Function functionA changes the value ofx to 25.

    To begin the program, variable x is initialized to 1.

    Function start changes the value ofx to 5.

  • 8/7/2019 jsFunctionArray

    19/58

    19

    10.9 JavaScript Global

    Functions Global object

    Always available

    Provides 7 methods

    Do not need to explicitly reference Globalbefore method call

    Also holds all global variables, user defined

    functions

  • 8/7/2019 jsFunctionArray

    20/58

    20

    10.9 JavaScript Global

    FunctionsGlobal function Descriptionescape This function takes a string argument and returns a

    string in which all spaces, punctuation, accent

    characters and any other character that is not in the

    ASCII character set (see Appendix D, ASCII

    Character Set) are encoded in a hexadecimal format

    (see Appendix E, Number Systems) that can be

    represented on all platforms.eval This function takes a string argument representing

    JavaScript code to execute. The JavaScript

    interpreter evaluates the code and executes it when

    the eval function is called. This function allows

    JavaScript code to be stored as strings and executed

    dynamically.isFinite This function takes a numeric argument and returns

    true if the value of the argument is not NaN,

    Number.POSITIVE_INFINITY or

    Number.NEGATIVE_INFINITY; otherwise, thefunction returns false.

    isNaN This function takes a numeric argument and returns

    true if the value of the argument is not a number;

    otherwise, it returns false. The function is

    commonly used with the return value ofparseInt

    orparseFloat to determine whether the result is a

    proper numeric value.

    Fig. 10.9 JavaScript global functions.

  • 8/7/2019 jsFunctionArray

    21/58

    21

    10.9 JavaScript Global

    FunctionsGlobal function DescriptionparseFloat This function takes a string argument and attempts

    to convert the beginning of the string into a floating-point value. If the conversion is unsuccessful, the

    function returns NaN; otherwise, it returns theconverted value (e.g., parseFloat("abc123.45" )returns NaN, and parseFloat("123.45abc")returns the value 123.45).

    parseInt This function takes a string argument and attempts

    to convert the beginning of the string into an integervalue. If the conversion is unsuccessful, the function

    returns NaN; otherwise, it returns the convertedvalue (e.g., parseInt("abc123") returns NaN, and

    parseInt("123abc")returns the integer value

    123). This function takes an optional secondargument, from 2 to 36, specifying the radix (or

    base) of the number. Base 2 indicates that the first

    argument string is in binary format, base 8 indicatesthat the first argument string is in octal format andbase 16 indicates that the first argument string is inhexadecimal format. See see Appendex E, Number

    Systems, for more information on binary, octal andhexadecimal numbers.

    unescape This function takes a string as its argument andreturns a string in which all characters previously

    encoded with escape are decoded.Fig. 10.9 JavaScript global functions.

  • 8/7/2019 jsFunctionArray

    22/58

    22

    10.10 Recursion

    Recursive functions Call themselves

    Recursion step or recursive call

    Part ofreturn

    statement

    Must have base case

    Simplest case of problem

    Returns value rather than calling itself

    Each recursive call simplifies input When simplified to base case, functions return

  • 8/7/2019 jsFunctionArray

    23/58

    23

    JavaScript: Functions and Arrays

    October 18, 2005

    Slides modified fromInternet & World Wide Web: How to Program. 2004 (3rd)edition. By Deitel, Deitel, and Goldberg. Published by

    Prentice Hall. ISBN 0-13-145091-3

  • 8/7/2019 jsFunctionArray

    24/58

    24

    Chapter 11 - JavaScript: Arrays

    Outline11.1 Introduction

    11.2 Arrays11.3 Declaring and Allocating Arrays

    11.4 Examples Using Arrays

    11.5 Random Image Generator Using Arrays

    11.6 References and Reference Parameters

    11.7 Passing Arrays to Functions

    11.8 Sorting Arrays11.9 Searching Arrays: Linear Search and Binary Search

    11.10 Multidimensional Arrays

    11.11 Building an Online Quiz

    11.12 Web Resources

  • 8/7/2019 jsFunctionArray

    25/58

    25

    Objectives

    In this tutorial, you will learn: To introduce the array data structure.

    To understand the use of arrays to store,

    sort and search lists and tables of values. To understand how to declare an array,

    initialize an array and refer to individual

    elements of an array.

    To be able to pass arrays to functions.

    To be able to search and sort an array.

    To be able to declare and manipulate multi-

    dimensional arrays.

  • 8/7/2019 jsFunctionArray

    26/58

    26

    11.1 Introduction

    Arrays

    Data structures of related items

    Also called Collections

    Dynamic

  • 8/7/2019 jsFunctionArray

    27/58

    27

    11.2 Arrays

    Arrays in JavaScript

    Each element referenced by a number

    Start at zeroth element

    Subscript or index

    Accessing a specific element

    Name of array

    Brackets Number of element

    Arrays know their length

    length property

  • 8/7/2019 jsFunctionArray

    28/58

    28

    11.2 Arrays

    c[ 6 ]

    -45

    6

    0

    72

    1543

    -89

    0

    62

    -3

    1

    6453

    78

    Name of array

    c[ 0 ]

    c[ 1 ]

    c[ 2 ]

    c[ 3 ]

    c[ 11 ]

    c[ 10 ]

    c[ 9 ]

    c[ 8 ]

    c[ 7 ]

    c[ 5 ]

    c[ 4 ]

    Position number (index

    or subscript) of theelement within array c

    Fig. 11.1 A 12-element array.

  • 8/7/2019 jsFunctionArray

    29/58

    29

    11.3 Declaring and

    Allocating Arrays

    Arrays in memory

    Objects

    Operatornew

    Allocates memory for objects Dynamic memory allocation operator

    var c;

    c = new Array( 12 );

    or

    var c = new Array( 12 );

  • 8/7/2019 jsFunctionArray

    30/58

    30

    11.4 Examples Using

    Arrays

    Arrays grow dynamically

    Allocate more space as items are added

    Must initialize array elements Default value is undefined

    for loops convenient

    Referring to uninitialized elements or

    elements outside array bounds is an error

    10 Initializing an Array

    11

  • 8/7/2019 jsFunctionArray

    31/58

    31

    11

    12

    13

    52

    53

    54

    55

  • 8/7/2019 jsFunctionArray

    32/58

    32

    11.4 Examples Using

    Arrays

    Possible to declare and initialize in one step

    Specify list of values

    Initializer list

    var n = [ 10, 20, 30, 40, 50 ];var n = new Array( 10, 20, 30, 40, 50 );

    Also possible to only initialize some values

    Leave uninitialized elements blank

    Uninitialized elements default to undefined

    var n = [ 10, 20, , 40, 50 ];

  • 8/7/2019 jsFunctionArray

    33/58

    33

    27

    28 // output "header" followed by a two-column table

    29 // containing subscripts and elements of "theArray"

    30 function outputArray( header, theArray )

    31 {

    32 document.writeln( "" + header + "" );

    33 document.writeln( "" );

    35 document.writeln( "Subscript" +

    37 "Value" );

    38

    39 for ( var i = 0; i < theArray.length; i++ )

    40 document.writeln( "" + i + "" +

    41 theArray[ i ] + "" );

    42

    43 document.writeln( "" );

    44 }

    45 // -->

    46

    47

    48

    49

    1

    2

    4

    5

    6

    7

    8

    9

    10 Initializing an Array with a Declaration

    11

    12

    13

  • 8/7/2019 jsFunctionArray

    34/58

    34

    11.4 Examples Using

    Arrays

    forin statement

    Perform an action for each element in an

    array

    Iterates over array elements

    Assigns each element to specified variable one at

    a time

    Ignores non-existent elements

  • 8/7/2019 jsFunctionArray

    35/58

    35

    SumArray.html

    (1 of 2)

    1

    2

    4

    5

    6

    7

    8

    9

    10 Sum the Elements of an Array

    11

    12

    13

    31

    32

    33

    34

    Variable element is assigned a subscript

    in the range of 0 up to, but not including,

    theArray.length.

    The for loop sums the values contained in the 10-

    element integer array called theArray.

  • 8/7/2019 jsFunctionArray

    36/58

    36

    11.4 Examples Using

    Arrays

    Arrays can provide shorter and cleanersubstitute forswitch statements

    Each element represents one case

    3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4

  • 8/7/2019 jsFunctionArray

    37/58

    37

    5

    6

    7

    8

    9

    10 Roll a Six-Sided Die 6000 Times

    11

    12

    13

    34

    35

    36

    37

    38

    Click Refresh (or Reload) to run the script again

    39

    40

  • 8/7/2019 jsFunctionArray

    38/58

    38

    11.5 Random Image

    Generator Using Arrays

    Cleaner approach than previous version

    Specify any file name rather than integers 1-7

    Result ofMath.random call is index into array

    of image file names

    1

  • 8/7/2019 jsFunctionArray

    39/58

    39

    RandomPicture2

    .html(1 of 2)

    1

    2

    4

    5

    6

    7

    8

    9

    10 Random Image Generator

    11

    12

    13

    21

    22

    23

    24

    25

    26

    Click Refresh (or Reload) to run the script again

    27

    28

  • 8/7/2019 jsFunctionArray

    40/58

    40

    11.6 References and

    Reference Parameters

    Two ways to pass parameters

    Pass-by-value

    Pass copy of original value

    Default for numbers, strings and booleans

    Original variable is unchanged

    Pass-by-reference

    How objects are passed, like arrays Pass location in memory of value

    Allows direct access to original value

    Improves performance

  • 8/7/2019 jsFunctionArray

    41/58

    41

    11.7 Passing Arrays to

    Functions

    Name of array is argument

    Not necessary to also pass size of array

    Arrays know their size

    Passed by reference

    Individual elements are passed by value if

    numbers, strings or booleans

    Array.join

    Creates string containing all array elements

    Specify separator

    12

  • 8/7/2019 jsFunctionArray

    42/58

    42

    PassArray.html

    (1 of 3)

    13

    14

  • 8/7/2019 jsFunctionArray

    43/58

    43

    PassArray.html

    (2 of 3)

    26 outputArray(

    27 "The values of the modified array are: ", a );

    28

    29 document.writeln( "Effects of passing array " +

    30 "element call-by-value" +

    31 "a[3] before modifyElement: " + a[ 3 ] );

    32

    33 modifyElement( a[ 3 ] );

    34

    35 document.writeln(

    36 "
    a[3] after modifyElement: " + a[ 3 ] );

    37 }

    38

    39 // outputs "header" followed by the contents of "theArray"

    40 function outputArray( header, theArray )

    41 {

    42 document.writeln(

    43 header + theArray.join( " " ) + "
    " );

    44 }

    45

    Again, function outputArray is called to show

    that the contents ofArray a have been modified.

    Method join takes as its argument a string

    containing a separator that should be used to

    separate the elements of the array in the string

    that is returned.

    Function modifyElementmultiplies the

    contents ofa[ 3 ] by 2.

    The value ofa[ 3 ] is output to show its

    contents before it is modified.

    46 // function that modifies the elements of an array

  • 8/7/2019 jsFunctionArray

    44/58

    44

    PassArray.html

    (3 of 3)

    46 // function that modifies the elements of an array

    47 function modifyArray( theArray )

    48 {

    49 for ( var j in theArray )

    50 theArray[ j ] *= 2;

    51 }

    52

    53 // function that attempts to modify the value passed

    54 function modifyElement( e )

    55 {

    56 e *= 2;

    57 document.writeln( "
    value in modifyElement: " + e );

    58 }

    59 // -->

    60

    61

    62

    63

    Multiply each element in theArray by 2.

  • 8/7/2019 jsFunctionArray

    45/58

    45

    11.8 Sorting Arrays

    Sorting

    Important computing task

    Array.sort

    Defaults to string comparison

    Optional comparator function

    Return negative if first argument less than second

    Return zero if arguments equal Return positive if first argument greater than

    second

    8

    9

  • 8/7/2019 jsFunctionArray

    46/58

    46

    Sort.html

    (1 of 2)

    10 Sorting an Array with Array Method sort

    11

    12

    13

    37

    38

    39

    40

    Function compareIntegers calculates the

    difference between the integer values of its

    arguments.

  • 8/7/2019 jsFunctionArray

    47/58

    47

    11.9 Searching Arrays: Linear

    Search and Binary Search

    Searching

    Look for matching key value

    Linear search

    Iterate through each element until match found

    Inefficient

    Worst case scenario, must test entire array

    Binary search

    Requires sorted data

    Cuts search range in half each iteration

    Efficient

    Only look at small fraction of elements

    8

    A is initiated with 100 elements

  • 8/7/2019 jsFunctionArray

    48/58

    48

    9

    10 Linear Search of an Array

    11

    12

    13

  • 8/7/2019 jsFunctionArray

    49/58

    49

    LinearSearch.html

    (3 of 3)

    y p y

    38 function linearSearch( theArray, key )

    39 {

    40 for ( var n = 0; n < theArray.length; ++n )

    41 if ( theArray[ n ] == key )

    42 return n;

    43

    44 return-1;

    45 }

    46 // -->

    47

    48

    49

    50

    51

    52

    53

    Enter integer search key

    54

    55

    57

    58

    Result

    59

    60

    61

    62

    Variable theArray gets the value of

    Array a and variable key gets the

    value of variable searchKey.Function linearSearch compares each

    each element with a search key.

  • 8/7/2019 jsFunctionArray

    50/58

    50

    11.9 Searching Arrays: Binary

    SearchFig. 11.11 Binary search of an array.

    11 10 M ltidi i l

  • 8/7/2019 jsFunctionArray

    51/58

    51

    11.10 Multidimensional

    Arrays

    Two-dimensional arrays analogous to

    tables

    Rows and columns

    Specify row first, then column

    Two subscripts

    11 10 M ltidi i l

  • 8/7/2019 jsFunctionArray

    52/58

    52

    11.10 Multidimensional

    Arrays

    a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]

    Row 0

    Row 1

    Row 2

    Column 0 Column 1 Column 2 Column 3

    Row subscript (or index)

    Array name

    Column subscript (or index)

    a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]

    a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

    Fig. 11.12 Two-dimensional array with three rows and four columns.

    11 10 M ltidi i l

  • 8/7/2019 jsFunctionArray

    53/58

    53

    11.10 Multidimensional

    Arrays

    Declaring and initializing multidimensional

    arrays

    Group by row in square brackets

    Treated as arrays of arrays

    Creating array b with one row of two elements

    and a second row of three elements:

    var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];

    11 10 M ltidi i l

  • 8/7/2019 jsFunctionArray

    54/58

    54

    11.10 Multidimensional

    Arrays

    Also possible to use new operator

    Create array b with two rows, first with five

    columns and second with three:

    var b;

    b = new Array( 2 );

    b[ 0 ] = new Array( 5 );

    b[ 1 ] = new Array( 3 );

    1

  • 8/7/2019 jsFunctionArray

    55/58

    55

    InitArray3.html

    (1 of 2)

    2

    4

    5

    6

    7

    8

    9

    10 Initializing Multidimensional Arrays

    11

    12

    13

  • 8/7/2019 jsFunctionArray

    56/58

    56

    InitArray3.html

    (2 of 2)

    26 function outputArray( header, theArray )

    27 {

    28 document.writeln( "" + header + "" );

    29

    30 for ( var i in theArray ) {

    3132 for ( var j in theArray[ i ] )

    33 document.write( theArray[ i ][ j ] + " " );

    34

    35 document.writeln( "
    " );

    36 }

    37

    38 document.writeln( "" );

    39 }

    40 // -->

    41

    42

    43

    44

    Referencing the multidimensional

    array theArray.

    11 11 B ildi O li

  • 8/7/2019 jsFunctionArray

    57/58

    57

    11.11 Building an Online

    Quiz

    Radio buttons

    Represented as an array

    Name of radio buttons is name of array

    One element per button

    checked property is true when selected

    XHTML Forms

    Contain controls, including radio buttons action property specifies what happens when

    submitted

    Can call JavaScript code

    10 Online Quiz

    11

    12

  • 8/7/2019 jsFunctionArray

    58/58

    58

    Quiz.html

    (2 of 2)

    26

    27

    28

    29

    Select the name of the tip that goes with the image shown:

    30

    31

    32

    33

    34 Common Programming Error

    35

    36

    37 Error-Prevention Tip

    38

    39

    40 Performance Tip

    41

    42

    43 Portability Tip

    44

    45

    46

    47

    48

    49 /b d

    Call the checkAnswers function

    when the form is submitted.

    13

    14 function checkAnswers()

    15 {

    16 // determine whether the answer is correct

    17 if ( myQuiz.radiobutton[ 1 ].checked )

    18 document.write( "Congratulations, your answer is correct" );

    19 else// if the answer is incorrect

    20 document.write( "Your answer is incorrect. Please try again" );

    21 }

    22

    23

    24

    25