Title: Chapter 6: JavaScript Functions
1Chapter 6 JavaScript Functions
- 6.1 The Purpose of Functions
- 6.2 Defining JavaScript Functions
- 6.3 Using JavaScript Functions
- 6.4 Global Functions and Event Handlers
- 6.5 Recursive Functions
- 6.6 Passing Values
- 6.7 Revisiting the sort() method.
2The Purpose of Functions
- Organizing solutions to computational problems.
- Creating reusable code.
- Sharing authorship of large projects
3Defining Functions
function doSomething(input1,input2,input3,...)
var local1,local2,local3,... local1 an
expression using one or more inputs... local2
an expression using one or more inputs and
(optionally) local1... local3 an
expression using one or more inputs and
(optionally) local1 and local2...
Do some calculations here with some
combination of parameters and local
variables... return a value
More than one return statement is allowed, but
only one value can be returned.
4JavaScript Function Model
The parameter list is a one-way path for input
only. Information can be passed in to the
function along this path, but no information
passes out along this path. The return
statement is a one-way path for a single value
flowing out of the function.
5Passing input "by value"
Document 6.1
lthtmlgtltheadgt lttitlegtCircle Area (1)lt/titlegt
ltbody bgcolor"99ccff"gt ltscript
language"javascript" type"text/javascript"gt
function getArea(r) return Math.PIrr
lt/scriptgtlt/headgtlth3gtCircle Area
(1)lt/h3gtltpgt ltformgt Enter radius, then press
tab key or click on "area" box.ltbr /gt
radius (cm) ltinput type"text" name"radius"
size"6" maxlength"7" value"-99",
onblur"area.valuegetArea(parseFloat(radius.value
))" /gt area (cmltsupgt2lt/supgt) ltinput
type"text" name"area" size"6" maxlength"7"
value"-99" /gtlt/formgtlt/bodygtlt/htmlgt
6Passing input by name
Document 6.2 (circle2.htm) Â lthtmlgtltheadgtlttitlegt
Circle Area (2)lt/titlegtltscript
language"javascript" type "text/javascript"gt
function getArea(r) var
radiusparseFloat(r.value) return
Math.PIparseFloat(r.value)parseFloat(r.value)
lt/scriptgtlt/headgt ltbodygtlth1gtCircle Area
(1)lt/h1gtltpgt ltformgt Enter radius, then press
tab key or click on "area" box.ltbr /gt radius
(cm) ltinput type"text" name"radius" size"6"
maxlength"7" value"-99", onblur
"area.valuegetArea(radius)"gt area
(cmltsupgt2lt/supgt) ltinput type"text"
name"area" size"6" maxlength"7"
value"-99"gtlt/formgtlt/bodygtlt/htmlgt
7Passing input through a form
Document 6.3 (circle3.htm) lthtmlgtltheadgtlttitlegtCi
rcle Area (4)lt/titlegtltscript language"javascript
" type "text/javascript"gt function getArea(f)
var rparseFloat(f.radius.value)
f.area.value Math.PIrr lt/scriptgtlt/headgt lt
bodygtlth1gtCircle Area (3)lt/h1gtltformgt Enter
radius, then press tab key or click on "area"
box.ltbr /gt radius (cm) ltinput type"text"
name"radius" size"6" maxlength"7"
value"-99", onblur "getArea(form)" /gt
area (cmltsupgt2lt/supgt) ltinput type"text"
name"area" size"6" maxlength"7"
value"-99" /gtlt/formgt lt/bodygt lt/htmlgt
Document 6.3 (circle3.htm) Â lthtmlgtltheadgtlttitlegt
Circle Area (4)lt/titlegtltscript
language"javascript" type "text/javascript"gt fu
nction getArea(f) var rparseFloat(f.radius.v
alue) f.area.value Math.PIrr lt/scriptgt
lt/headgt ltbodygtlth1gtCircle Area (3)lt/h1gtltformgt
Enter radius, then press tab key or click on
"area" box.ltbr /gt radius (cm) ltinput
type"text" name"radius" size"6"
maxlength"7" value"-99", onblur
"getArea(form)" /gt area (cmltsupgt2lt/supgt)
ltinput type"text" name"area" size"6"
maxlength"7" value"-99" /gtlt/formgt lt/bodygt lt/htm
lgt
You have to know the name of the form field.
There is no return statement.
8Returning multiple outputs with a form
Document 6.4 (circleStuff.htm) ltscript
language"javascript" type "text/javascript"gt fu
nction circleStuff(f) var rparseFloat(f.radi
us.value) f.area.valueMath.PIrr
f.circumference.value2.Math.PIr lt/scriptgt
9Using the elements array
function circleStuff(f) var rparseFloat(f.elem
ents0.value) f.elements1.valueMath.PIrr
f.elements2.value2.Math.PIr
You don't need to know the field names, but you
need to know their order and interpretation.
10Returning Multiple Values in an Array
Document 6.5 (circleStuff2.htm) ltscript
language"javascript" type "text/javascript"gt
function circleStuff(r) var A Array()
A0 Math.PIrr A1 2.Math.PIr
return A lt/scriptgt ltformgt Enter
radius, then press tab key or click on "area" or
"circumference field.ltbr /gt radius (cm)
ltinput type"text" name"radius" size"6"
maxlength"7" value"-99", onblur "var A
Array() A circleStuff(parseFloat(radius.va
lue)) area.value A0 circumference.value
A1 " /gt area (cmltsupgt2lt/supgt) ltinput
type"text" name"area" size"6"
maxlength"7" value"-99" /gt circumference(cm)
ltinput type"text" name"circumference"
size"6" maxlength"7" value"-99"
/gtlt/formgt
You dont have to know anything about the field
names.
You have to know what each array element contains.
11Global Methods
Table 6.1. (partial) Some Global methods for
evaluating and converting strings.
12Using ParseInt()
Document 6.6 (parseIntBug.htm) lthtmlgtltheadgtlttit
legtparseInt() "bug"lt/titlegtlt/headgtltbodygtltformgt
integer value ltinput name"x" value"09" /gtltbr
/gtClick for parseInt("string") result ltinput
name"x_int" onclick"x_int.valueparseInt(x.va
lue) " /gtltbr /gtClick for parseInt("string",10)
result ltinput name"x_int10"
onclick"x_int10.valueparseInt(x.value,10) "
/gtltbr /gtClick for parseFloat("string") result
ltinput name "x_float" onclick"x_float.valuep
arseFloat(x.value) " /gtlt/formgtlt/bodygtlt/htmlgt
13Using the eval() method
Document 6.7 (calculator.htm) lthtmlgtltheadgtlttitle
gtSimple Calculatorlt/titlegtlt/headgtltbodygtltformgt
Type expression to be evaluated, using numbers
and , -, , / ltinput type"text"
name"expression" size"30" maxlength"30"
onchange"result.valueeval(expression.value)"
/gt ltinput type"text" name"result" size"8"
maxlength"8" /gtlt/formgtlt/bodygtlt/htmlgt
14Event Handlers
Table 6.2. Summary of some event handlers used in
forms.
Table 6.2. Summary of some event handlers used in
forms.
Table 6.2. Summary of some event handlers used in
forms.
15Recursive Functions
- Recursive functions call themselves.
- n! defined for non-negative integers n!
n(n-1)(1) - n! n(n-1)!, ngt1
- n! 1, n1 or n1
Document 6.8 (factorial2.htm) Â lthtmlgtlttitlegtCalc
ulate n!lt/titlegtltbodygtltscript
language"JavaScript" type"text/javascript"gtfunc
tion nFactorial(n) if (nlt1) return 1 else
return nnFactorial(n-1) lt/scriptgtlt/headgtlth1
gtCalculate n factorial (n!)lt/h1gtltpgt ltformgt
Enter n (a non-negative integer) ltinput
type"text" name"n" size"2" maxlength"3"
value"0" onblur"factorial.value
nFactorial(parseInt(n.value,10))" /gt (Press
Tab to get n!.)ltbrgt ltinput type"text"
name"factorial" size"10" maxlength"11"
value"1" /gt ltbr /gtlt/formgtlt/bodygtlt/htmlgt
16Tracking recursive calls
17Fibonacci Numbers
Document 6.9 (fibonacci.htm) lthtmlgtlttitlegtCalcula
te Fibonacci numberslt/titlegtltbody
bgcolor"99ccff"gtltscript language"JavaScript"
type"text/javascript"gt function Fib(n)
if (nlt2) return 1 else return
Fib(n-1)Fib(n-2) lt/scriptgtlt/headgtlth1gtCalcu
late the nltsupgtthlt/supgt Fibonacci numberlt/h1gtltpgt
ltformgt Enter n (a positive integer) ltinput
type"text" name"n" size"2" maxlength"3"
value"1" onblur"FibN.valueFib(parseInt(n.valu
e))" /gt (Press Tab to get nltsupgtthlt/supgt
Fibonacci number.)ltbrgt ltinput type"text"
name"FibN" size"8" maxlength"8" value"1"
/gtlt/formgtlt/bodygtlt/htmlgt
18The Towers of Hanoi Problem
Consider three poles, on one of which are
stacked 64 golden rings. The bottom ring is the
largest and the others decrease in size. The
object is to move the 64 rings from one pole to
another, using the remaining pole as a temporary
storage place for rings. There are two rules
for moving rings 1. Only one ring can be moved
at a time. 2. A ring can never be placed on top
of a smaller ring. Describe how to move the
entire stack of rings from one pole to another.
The algorithm 1.Move n-1 rings from A to
B. 2.Move the nth ring from A to C. 3.Move n-1
rings from B to C.
19Towers of Hanoi Solution
Document 6.10 (towers.htm) lthtmlgtltheadgtlttitlegt
lt/titlegtltscript language"javascript"
type"text/javascript"gt function
move(n,start,end,intermediate) if (n gt "0")
move(n-1,start,intermediate,end)
document.write("move ring "n " from
"start" to "end".ltbr /gt")
move(n-1,intermediate,end,start)
var nprompt("Give n") move(n,"A","C","B")
lt/scriptgtlt/headgtltbodygtlt/bodygtlt/htmlgt
20Pass ID
Document 6.11(a) (passID.htm) lthtmlgtltheadgtlttitlegt
Get ID and password.lt/titlegtltscript
language"javascript" type"text/javascript"gt
function checkIDPW() var PWinputlogin_form.
PW.value var IDinputlogin_form.ID.value
var flagprompt("ID "IDinput ", PW
"PWinput". OK (y or n)?") if (flag "y")
return true else return false
lt/scriptgtlt/headgtltbodygt ltform method"link"
action"catchID.htm" name"login_form"
onsubmit"checkIDPW()"gt ID ltinput type"text"
name"ID"gt PW ltinput type"text" name"PW"gt
ltinput type"submit" value"Access protected
page."gtlt/formgtlt/bodygtlt/htmlgt
21Catch ID
Document 6.11(b) (catchID.htm) lthtmlgtltheadgtlttitle
gtReceive ID and password from another
document.lt/titlegtlt/headgtltbodygtltform
name"catchForm"gtltinput type"hidden"
name"info"gtlt/formgtltscript language"javascript"
type"text/javascript"gtcatchForm.info.valuewindo
w.location // alert(window.location)function
getID(str) theleftstr.indexOf("")1
therightstr.lastIndexOf("") return
str.substring(theleft,theright)function
getPW(str) theleftstr.lastIndexOf("")1
return str.substring(theleft)document.write("I
D is "getID(catchForm.info.value) ", PW is
"getPW(catchForm.info.value)) lt/scriptgtlt/bodygtlt/
htmlgt
22sort() revisited
Document 6.12 (sort2.htm)
lthtmlgtltheadgtlttitlegtSorting Arrayslt/titlegtltscrip
t language"javascript" type"text/javascript"gt
function compare(x,y) var XparseFloat(x)
YparseFloat(y) if (XltY) return -1
else if (XY) return 0 else return 1
var a7,5,13,3 var i alert(a "
length of a " a.length) a.sort(compare)
alert(a " length of a "
a.length)lt/scriptgtlt/headgt ltbodygtlt/bodygtlt/htm
lgt
23Dewpoint Temperature
Document 6.13 (dewpoint.htm)
ltscript language"JavaScript" type"text/javascrip
t"gt function getDewpoint(T,RH) var
a17.27,b237.7,alpha var tempparseFloat(T.v
alue) var rhparseFloat(RH.value)/100.
alphaatemp/(btemp)Math.log(rh) return
Math.round(balpha/(a-alpha)10.)/10.
lt/scriptgt
onclick"DP.valuegetDewpoint(T,RH)" /gt
24Monthly Loan Payment
Document 6.14 (loan.htm)
ltscript language"JavaScript" type"text/javascrip
t"gt function getPayment(P,r,n)
rr/100./12. var MPr/(1.-1./Math.pow(1.r,n)
) return M.toFixed(2) lt/scriptgt
onclick "monthly.valuegetPayment(parseFloat(a
mount.value), parseFloat(rate.value),parseInt(
n.value))"
25Array-derived Pull-down Menus
Document 6.16 (buildMenu.htm) Â lthtmlgtltheadgtlttit
legtBuild a variable-length pull-down
menult/titlegt ltbody onload"buildSelect(menuForm.
stuff,listItems)" gtltform name"menuForm"
gtHere's the menultbr /gtClick on an item to
select it.ltbr /gtltselect name"stuff" size"10"
onchange"listChoice.valuegetSelected(stuff)
"gtlt/selectgtltbr /gtThis is the item
selectedltinput type"text" name"listChoice"
value""/gtlt/formgtlt/bodygtlt/htmlgt
Build menu when this application loads.
26Array-derived Pull-down Menus (concluded)
ltscript language"javascript" type"text/javascrip
t"gt var listItems new Array()
listItems0"thing1" listItems1"thing2"
listItems2"thing3" listItems3"things4"
listItems4"newthing" function
buildSelect(list,things) var
i//alert(things) for (i0 iltthings.length
i) list.optionsinew Option(thingsi,th
ingsi) function getSelected(list)
var i for (i0 iltlist.length i) if
(list.optionsi.selected) return
list.optionsi.value lt/scriptgt