280 likes | 523 Views
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.
E N D
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 • Organizing solutions to computational problems. • Creating reusable code. • Sharing authorship of large projects
Defining 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.
JavaScript 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.
Passing input "by value" Document 6.1 <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>
Passing input “by name” Document 6.2 (circle2.htm) <html><head><title>Circle Area (2)</title><script language="javascript" type ="text/javascript"> functiongetArea(r) { var radius=parseFloat(r.value); returnMath.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>
Document 6.3 (circle3.htm) <html><head><title>Circle Area (4)</title><script language="javascript" type ="text/javascript">functiongetArea(f) {varr=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> Passing input through a form Document 6.3 (circle3.htm) <html><head><title>Circle Area (4)</title><script language="javascript" type ="text/javascript">functiongetArea(f) {varr=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 the name of the form field. There is no return statement.
Returning multiple outputs with a form Document 6.4 (circleStuff.htm) … <script language="javascript" type ="text/javascript">functioncircleStuff(f) {varr=parseFloat(f.radius.value);f.area.value=Math.PI*r*r;f.circumference.value=2.*Math.PI*r; }</script>
Using the elements array… functioncircleStuff(f) { varr=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 know their order and interpretation.
Returning Multiple Values in an Array Document 6.5 (circleStuff2.htm) … <script language="javascript" type ="text/javascript">functioncircleStuff(r) {varA = Array(); A[0] = Math.PI*r*r;A[1] = 2.*Math.PI*r; returnA; }</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 = "varA = 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 anything about the field names. You have to know what each array element contains.
Global Methods Table 6.1. (partial) Some Global methods for evaluating and converting strings.
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>
Using the eval() method Document 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>
Table 6.2. Summary of some event handlers used in forms. Table 6.2. Summary of some event handlers used in forms. Event Handlers Table 6.2. Summary of some event handlers used in forms.
Recursive Functions Document 6.8 (factorial2.htm) <html><title>Calculate n!</title><body><script language="JavaScript" type="text/javascript">functionnFactorial(n) {if (n<=1) return 1;elsereturnn*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> • Recursive functions call themselves. • n! defined for non-negative integers: n! = n*(n-1)*…*(1) n! = n*(n-1)!, n>1 n! = 1, n=1 or n=1
Fibonacci Numbers Document 6.9 (fibonacci.htm) <html><title>Calculate Fibonacci numbers</title><body bgcolor="#99ccff"><script language="JavaScript" type="text/javascript">functionFib(n) {if (n<=2) return 1;elsereturnFib(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>
The 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.
Towers of Hanoi Solution Document 6.10 (towers.htm) <html><head><title></title><script language="javascript" type="text/javascript">functionmove(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); } } varn=prompt("Give n:");move(n,"A","C","B");</script></head><body></body></html>
Pass ID Document 6.11(a) (passID.htm) <html><head><title>Get ID and password.</title><script language="javascript" type="text/javascript">functioncheckIDPW() {varPWinput=login_form.PW.value;varIDinput=login_form.ID.value;varflag=prompt("ID = "+IDinput+ ", PW = "+PWinput+". OK (y or n)?");if (flag == "y") returntrue; elsereturnfalse; }</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>
Catch ID Document 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);functiongetID(str){theleft=str.indexOf("=")+1;theright=str.lastIndexOf("&");returnstr.substring(theleft,theright);}functiongetPW(str) {theleft=str.lastIndexOf("=")+1;returnstr.substring(theleft);}document.write("ID is "+getID(catchForm.info.value)+ ", PW is "+getPW(catchForm.info.value)); </script></body></html>
sort()revisited Document 6.12 (sort2.htm) <html><head><title>Sorting Arrays</title><script language="javascript" type="text/javascript">functioncompare(x,y) {varX=parseFloat(x); Y=parseFloat(y);if (X<Y) return -1; elseif (X==Y) return 0;elsereturn 1; }vara=[7,5,13,3];vari;alert(a + " length of a = " + a.length);a.sort(compare);alert(a + " length of a = " + a.length);</script></head><body></body></html>
Dewpoint Temperature Document 6.13 (dewpoint.htm) <script language="JavaScript" type="text/javascript">functiongetDewpoint(T,RH) {vara=17.27,b=237.7,alpha;vartemp=parseFloat(T.value);varrh=parseFloat(RH.value)/100.;alpha=a*temp/(b+temp)+Math.log(rh); returnMath.round(b*alpha/(a-alpha)*10.)/10.; }</script> onclick="DP.value=getDewpoint(T,RH)" />
Monthly Loan Payment Document 6.14 (loan.htm) <script language="JavaScript" type="text/javascript">functiongetPayment(P,r,n) {r=r/100./12.;varM=P*r/(1.-1./Math.pow(1.+r,n));returnM.toFixed(2) }</script> onclick= "monthly.value=getPayment(parseFloat(amount.value), parseFloat(rate.value),parseInt(n.value));"
Array-derived Pull-down Menus 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 this application loads.
Array-derived Pull-down Menus (concluded) <script language="javascript" type="text/javascript">varlistItems = newArray();listItems[0]="thing1";listItems[1]="thing2";listItems[2]="thing3";listItems[3]="things4";listItems[4]="newthing";functionbuildSelect(list,things) {vari;//alert(things);for (i=0; i<things.length; i++)list.options[i]=newOption(things[i],things[i]); }functiongetSelected(list) {vari;for (i=0; i<list.length; i++)if (list.options[i].selected) returnlist.options[i].value; }</script>