JavaScript: Functions and Arrays - PowerPoint PPT Presentation

1 / 58
About This Presentation
Title:

JavaScript: Functions and Arrays

Description:

JavaScript: Functions and Arrays October 18, 2005 Slides modified from Internet & World Wide Web: How to Program. 2004 (3rd) edition. By Deitel, Deitel, and Goldberg. – PowerPoint PPT presentation

Number of Views:1459
Avg rating:3.0/5.0
Slides: 59
Provided by: oldChitu
Category:

less

Transcript and Presenter's Notes

Title: JavaScript: Functions and Arrays


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

2
Chapter 10 - JavaScript Functions
Outline 10.1 Introduction 10.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
Generator 10.8 Scope Rules 10.9 JavaScript
Global Functions 10.10 Recursion 10.11
Recursion vs. Iteration 10.12 Web Resources
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 use
    random-number generation.
  • To understand how the visibility of identifiers
    is limited to specific regions of programs.

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

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 )

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

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

9
10.4 Function Definitions
  • Writing a function to square two numbers
  • for loop from 1 to 10
  • Pass each number as argument to square
  • return value of argument multiplied by itself
  • Display result

10
(No Transcript)
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 )

12
(No Transcript)
13
RollDie.html(3 of 3)
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

15
RandomPicture.html(1 of 1)
Inserting a random number into the images src
property with document.write and Math.random
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

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 to 25
  • functionB has no local variable x
  • Observe output of each function

18
To begin the program, variable x is initialized
to 1.
Function start changes the value of x to 5.
Function functionA changes the value of x to 25.
The value of x is incremented.
Function functionB multiplies the value of x by
10.
19
10.9 JavaScript Global Functions
  • Global object
  • Always available
  • Provides 7 methods
  • Do not need to explicitly reference Global before
    method call
  • Also holds all global variables, user defined
    functions

20
10.9 JavaScript Global Functions
21
10.9 JavaScript Global Functions
22
10.10 Recursion
  • Recursive functions
  • Call themselves
  • Recursion step or recursive call
  • Part of return 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

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

24
Chapter 11 - JavaScript Arrays
Outline 11.1 Introduction 11.2 Arrays 11.3
Declaring and Allocating Arrays 11.4 Examples
Using Arrays11.5 Random Image Generator Using
Arrays 11.6 References and Reference
Parameters 11.7 Passing Arrays to
Functions 11.8 Sorting Arrays 11.9 Searching
Arrays Linear Search and Binary Search 11.10
Multidimensional Arrays11.11 Building an Online
Quiz 11.12 Web Resources
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.

26
11.1 Introduction
  • Arrays
  • Data structures of related items
  • Also called Collections
  • Dynamic

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

28
11.2 Arrays
-45
c 0
Name of array
6
c 1
0
c 2
72
c 3
1543
c 4
-89
c 5
c 6
0
62
c 7
-3
c 8
1
c 9
Position number (index
or subscript) of the
6453
c 10
c
element within array
78
c 11
Fig. 11.1 A 12-element array.
29
11.3 Declaring and Allocating Arrays
  • Arrays in memory
  • Objects
  • Operator new
  • Allocates memory for objects
  • Dynamic memory allocation operator
  • var cc new Array( 12 )
  • or
  • var c new Array( 12 )

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

31
(No Transcript)
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

33
(No Transcript)
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

35
SumArray.html(1 of 2)
Variable element is assigned a subscript in the
range of 0 up to, but not including,
theArray.length.
36
11.4 Examples Using Arrays
  • Arrays can provide shorter and cleaner substitute
    for switch statements
  • Each element represents one case

37
(No Transcript)
38
11.5 Random Image Generator Using Arrays
  • Cleaner approach than previous version
  • Specify any file name rather than integers 1-7
  • Result of Math.random call is index into array of
    image file names

39
RandomPicture2.html(1 of 2)
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

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

42
PassArray.html(1 of 3)
43
PassArray.html(2 of 3)
44
PassArray.html(3 of 3)
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

46
Sort.html(1 of 2)
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

48
LinearSearch.html(2 of 3)
49
LinearSearch.html(3 of 3)
50
11.9 Searching Arrays Binary Search
Fig. 11.11 Binary search of an array.
51
11.10 Multidimensional Arrays
  • Two-dimensional arrays analogous to tables
  • Rows and columns
  • Specify row first, then column
  • Two subscripts

52
11.10 Multidimensional Arrays
Column 0
Column 1
Column 2
Column 3
a 0 0
a 0 1
a 0 2
a 0 3
Row 0
a 1 0
a 1 1
a 1 2
a 1 3
Row 1
a 2 0
a 2 1
a 2 2
a 2 3
Row 2
Column subscript (or index)
Row subscript (or index)
Array name
Fig. 11.12 Two-dimensional array with three
rows and four columns.
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

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 )

55
InitArray3.html(1 of 2)
56
InitArray3.html(2 of 2)
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

58
Quiz.html(2 of 2)
Write a Comment
User Comments (0)
About PowerShow.com