26
Chapter 6: JavaScript Chapter 6: JavaScript Functions 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.

Chapter 6: JavaScript Functions

  • Upload
    sorcha

  • View
    49

  • Download
    1

Embed Size (px)

DESCRIPTION

Chapter 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. The Purpose of Functions. - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 6: JavaScript Functions

Chapter 6: JavaScript FunctionsChapter 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.

Page 2: Chapter 6: JavaScript Functions

The Purpose of FunctionsThe Purpose of Functions

Organizing solutions to computational problems.

Creating reusable code. Sharing authorship of large projects

Page 3: Chapter 6: JavaScript Functions

Defining FunctionsDefining Functionsfunction 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.

Page 4: Chapter 6: JavaScript Functions

JavaScript Function ModelJavaScript 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.

Page 5: Chapter 6: JavaScript Functions

Passing input "by value"Passing input "by value"

<html><head> <title>Circle Area (1)</title> <body bgcolor="#99ccff"> <script language="javascript" type="text/javascript"> function getArea(r) { return Math.PI*r*r; } </script></head><h3>Circle Area (1)</h3><p> <form> Enter radius, then press tab key or click on "area" box.<br /> radius (cm): <input type="text" name="radius" size="6" maxlength="7" value="-99", onblur="area.value=getArea(parseFloat(radius.value));" /> area (cm<sup>2</sup>): <input type="text" name="area" size="6" maxlength="7"

value="-99" /></form></body></html>

Document 6.1

Page 6: Chapter 6: JavaScript Functions

Passing input “by name”Passing input “by name”Document 6.2 (circle2.htm) <html><head><title>Circle Area (2)</title><script language="javascript" type ="text/javascript"> function getArea(r) { var radius=parseFloat(r.value); return Math.PI*parseFloat(r.value)*parseFloat(r.value); }</script></head><body><h1>Circle Area (1)</h1><p> <form> Enter radius, then press tab key or click on "area" box.<br /> radius (cm): <input type="text" name="radius" size="6" maxlength="7" value="-99", onblur = "area.value=getArea(radius);"> area (cm<sup>2</sup>): <input type="text" name="area" size="6" maxlength="7" value="-99"></form></body></html>

Page 7: Chapter 6: JavaScript Functions

Passing input through a formPassing input through a formDocument 6.3 (circle3.htm) <html><head><title>Circle Area (4)</title><script language="javascript" type ="text/javascript">

function getArea(f) { var r=parseFloat(f.radius.value); f.area.value = Math.PI*r*r;}

</script></head><body><h1>Circle Area (3)</h1><form> Enter radius, then press tab key or click on "area" box.<br /> radius (cm): <input type="text" name="radius" size="6" maxlength="7" value="-99", onblur = "getArea(form);" /> area (cm<sup>2</sup>): <input type="text" name="area" size="6" maxlength="7" value="-99" /></form></body></html>

You have to know thename of the form field.

Document 6.3 (circle3.htm)<html><head><title>Circle Area (4)</title><script language="javascript" type ="text/javascript">

function getArea(f) { var r=parseFloat(f.radius.value); f.area.value = Math.PI*r*r;}

</script></head><body><h1>Circle Area (3)</h1><form> Enter radius, then press tab key or click on "area" box.<br /> radius (cm): <input type="text" name="radius" size="6" maxlength="7" value="-99", onblur = "getArea(form);" /> area (cm<sup>2</sup>): <input type="text" name="area" size="6" maxlength="7" value="-99" /></form></body></html>

There is no return statement.

Page 8: Chapter 6: JavaScript Functions

Returning multiple outputs with a Returning multiple outputs with a formform

Document 6.4 (circleStuff.htm)

…<script language="javascript" type ="text/javascript">

function circleStuff(f) { var r=parseFloat(f.radius.value); f.area.value=Math.PI*r*r; f.circumference.value=2.*Math.PI*r;}

</script>

Page 9: Chapter 6: JavaScript Functions

Using the Using the elements array… array…

function circleStuff(f) {var r=parseFloat(f.elements[0].value);f.elements[1].value=Math.PI*r*r;f.elements[2].value=2.*Math.PI*r;

}

You don't need to know the field names, but you need to knowtheir order and interpretation.

Page 10: Chapter 6: JavaScript Functions

Returning Multiple Values in an Returning Multiple Values in an ArrayArrayDocument 6.5 (circleStuff2.htm)

…<script language="javascript" type ="text/javascript"> function circleStuff(r) { var A = Array(); A[0] = Math.PI*r*r; A[1] = 2.*Math.PI*r; return A; }</script>…<form> Enter radius, then press tab key or click on "area" or "circumference field.<br /> radius (cm): <input type="text" name="radius" size="6" maxlength="7" value="-99", onblur = "var A = Array(); A = circleStuff(parseFloat(radius.value)); area.value = A[0]; circumference.value = A[1]; " /> area (cm<sup>2</sup>): <input type="text" name="area" size="6" maxlength="7" value="-99" /> circumference(cm): <input type="text" name="circumference" size="6" maxlength="7" value="-99" /></form>…

You don’t have to know anythingabout the field names.

You have to know what eacharray element contains.

Page 11: Chapter 6: JavaScript Functions

Global MethodsGlobal MethodsTable 6.1. (partial) Some Global methods for evaluating and converting strings.

Global method Description Example

eval("s")Evaluates string "s" as though it were JavaScript code.

Eval("3+4/5") returns a value of 3.8.

isNaN("s")Returns “true” if the argument cannot be interpreted as a number, “false” otherwise.

isNaN("a17”) returns a value of true.

parseFloat("s")Converts a string to a real (floating point) number.

parseFloat("17.7") returns a value of 17.7.

parseInt("s",b)

Converts a string to an integer number using base “b” arithmetic.

parseInt("17.7",10) returns a value of 17.

Page 12: Chapter 6: JavaScript Functions

Using Using ParseInt()Document 6.6 (parseIntBug.htm)

<html><head><title>parseInt() "bug"</title></head><body><form>integer value: <input name="x" value="09" /><br />Click for parseInt("string") result: <input name="x_int" onclick="x_int.value=parseInt(x.value); " /><br />Click for parseInt("string",10) result: <input name="x_int10" onclick="x_int10.value=parseInt(x.value,10); " /><br />Click for parseFloat("string") result: <input name= "x_float" onclick="x_float.value=parseFloat(x.value); " /></form></body></html>

Page 13: Chapter 6: JavaScript Functions

Using the Using the eval()eval() method methodDocument 6.7 (calculator.htm)<html><head><title>Simple Calculator</title></head><body><form> Type expression to be evaluated, using numbers and +, -, *, /: <input type="text" name="expression" size="30" maxlength="30" onchange="result.value=eval(expression.value);" /> <input type="text" name="result" size="8"

maxlength="8" /></form></body></html>

Page 14: Chapter 6: JavaScript Functions

Event HandlersEvent HandlersTable 6.2. Summary of some event handlers used in forms.

Event handler

Action

onblurInitiates action when a user tabs from a form field or clicks elsewhere in a document.

onchangeInitiates action when a user changes the contents of a form field.

onclickInitiates action when a user clicks on form input field.

onfocusInitiates action when a user tabs to or clicks on a form field.

onloadInside a <body> tag, initiates action when a document is loaded into the user’s browser.

Table 6.2. Summary of some event handlers used in forms.

Table 6.2. Summary of some event handlers used in forms.

Page 15: Chapter 6: JavaScript Functions

Recursive FunctionsRecursive Functions Recursive functions call themselves. n! defined for non-negative integers: n! = n*(n-1)*…*(1)

n! = n*(n-1)!, n>1n! = 1, n=1 or n=1

Document 6.8 (factorial2.htm) <html><title>Calculate n!</title><body><script language="JavaScript" type="text/javascript">function nFactorial(n) {

if (n<=1) return 1;else return n*nFactorial(n-1);

}</script></head><h1>Calculate n factorial (n!)</h1><p> <form> Enter n (a non-negative integer): <input type="text" name="n" size="2" maxlength="3" value="0" onblur="factorial.value= nFactorial(parseInt(n.value,10));" /> (Press Tab to get n!.)<br> <input type="text" name="factorial" size="10" maxlength="11" value="1" /> <br /></form></body></html>

Page 16: Chapter 6: JavaScript Functions

Tracking recursive callsTracking recursive calls

Local value of nAction

Value returned

n = 4 Initial call Deferred

n = 3 1st recursive call Deferred

n = 2 2nd recursive call Deferred

n = 1 3rd recursive call 1

n = 2 Complete multiplication 2·1 2

n = 3 Complete multiplication 3·2 6

n = 4 Complete multiplication 4·6 24

Page 17: Chapter 6: JavaScript Functions

Fibonacci NumbersFibonacci NumbersDocument 6.9 (fibonacci.htm)<html><title>Calculate Fibonacci numbers</title><body bgcolor="#99ccff"><script language="JavaScript" type="text/javascript"> function Fib(n) { if (n<=2) return 1; else return Fib(n-1)+Fib(n-2); }</script></head><h1>Calculate the n<sup>th</sup> Fibonacci number</h1><p> <form> Enter n (a positive integer): <input type="text" name="n" size="2" maxlength="3" value="1" onblur="FibN.value=Fib(parseInt(n.value));" /> (Press Tab to get n<sup>th</sup> Fibonacci number.)<br> <input type="text" name="FibN" size="8" maxlength="8" value="1" /></form></body></html>

Page 18: Chapter 6: JavaScript Functions

The Towers of Hanoi ProblemThe 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.

Page 19: Chapter 6: JavaScript Functions

Towers of Hanoi SolutionTowers of Hanoi SolutionDocument 6.10 (towers.htm)

<html><head><title></title><script language="javascript" type="text/javascript"> function move(n,start,end,intermediate) { if (n > "0") { move(n-1,start,intermediate,end); document.write("move ring "+n+ " from "+start+" to "+end+".<br />"); move(n-1,intermediate,end,start); } }

var n=prompt("Give n:"); move(n,"A","C","B");</script></head><body></body></html>

Page 20: Chapter 6: JavaScript Functions

Pass IDPass IDDocument 6.11(a) (passID.htm)<html><head><title>Get ID and password.</title><script language="javascript" type="text/javascript"> function checkIDPW() { var PWinput=login_form.PW.value; var IDinput=login_form.ID.value; var flag=prompt("ID = "+IDinput+ ", PW = "+PWinput+". OK (y or n)?"); if (flag == "y") return true; else return false; }</script></head><body> <form method="link" action="catchID.htm" name="login_form" onsubmit="checkIDPW();"> ID: <input type="text" name="ID"> PW: <input type="text" name="PW"> <input type="submit" value="Access protected page."></form></body></html>

Page 21: Chapter 6: JavaScript Functions

Catch IDCatch IDDocument 6.11(b) (catchID.htm)<html><head><title>Receive ID and password from another document.</title></head><body><form name="catchForm"><input type="hidden" name="info"></form><script language="javascript" type="text/javascript">catchForm.info.value=window.location;// alert(window.location);function getID(str){ theleft=str.indexOf("=")+1; theright=str.lastIndexOf("&"); return str.substring(theleft,theright);}function getPW(str) { theleft=str.lastIndexOf("=")+1; return str.substring(theleft);}document.write("ID is "+getID(catchForm.info.value)+ ", PW is "+getPW(catchForm.info.value));</script></body></html>

Page 22: Chapter 6: JavaScript Functions

sort() revisitedrevisitedDocument 6.12 (sort2.htm)

<html><head><title>Sorting Arrays</title><script language="javascript" type="text/javascript"> function compare(x,y) { var X=parseFloat(x); Y=parseFloat(y); if (X<Y) return -1; else if (X==Y) return 0; else return 1; } var a=[7,5,13,3]; var i; alert(a + " length of a = " + a.length); a.sort(compare); alert(a + " length of a = " + a.length);</script></head> <body></body></html>

Page 23: Chapter 6: JavaScript Functions

Dewpoint TemperatureDewpoint TemperatureDocument 6.13 (dewpoint.htm)

<script language="JavaScript" type="text/javascript"> function getDewpoint(T,RH) { var a=17.27,b=237.7,alpha; var temp=parseFloat(T.value); var rh=parseFloat(RH.value)/100.; alpha=a*temp/(b+temp)+Math.log(rh);

return Math.round(b*alpha/(a-alpha)*10.)/10.; }</script>

onclick="DP.value=getDewpoint(T,RH)" />

Page 24: Chapter 6: JavaScript Functions

Monthly Loan PaymentMonthly Loan Payment

Document 6.14 (loan.htm)

<script language="JavaScript" type="text/javascript">function getPayment(P,r,n) { r=r/100./12.; var M=P*r/(1.-1./Math.pow(1.+r,n)); return M.toFixed(2)}

</script>

onclick= "monthly.value=getPayment(parseFloat(amount.value), parseFloat(rate.value),parseInt(n.value));"

Page 25: Chapter 6: JavaScript Functions

Array-derived Pull-down Array-derived Pull-down MenusMenus

Document 6.16 (buildMenu.htm) <html><head><title>Build a variable-length pull-down menu</title>…<body onload="buildSelect(menuForm.stuff,listItems);" ><form name="menuForm" >Here's the menu:<br />Click on an item to select it.<br /><select name="stuff" size="10" onchange="listChoice.value=getSelected(stuff); "></select><br />This is the item selected:<input type="text" name="listChoice" value=""/></form></body></html>

Build menu when thisapplication loads.

Page 26: Chapter 6: JavaScript Functions

Array-derived Pull-down Menus Array-derived Pull-down Menus (concluded)(concluded)

<script language="javascript" type="text/javascript"> var listItems = new Array(); listItems[0]="thing1"; listItems[1]="thing2"; listItems[2]="thing3"; listItems[3]="things4"; listItems[4]="newthing"; function buildSelect(list,things) { var i;//alert(things); for (i=0; i<things.length; i++) list.options[i]=new Option(things[i],things[i]); } function getSelected(list) { var i; for (i=0; i<list.length; i++) if (list.options[i].selected) return list.options[i].value; }</script>