Download presentation
Presentation is loading. Please wait.
Published byKory Mowbray Modified over 9 years ago
1
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.
2
The Purpose of Functions Organizing solutions to computational problems. Creating reusable code. Sharing authorship of large projects
3
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.
4
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.
5
Passing input "by value" Circle Area (1) function getArea(r) { return Math.PI*r*r; } Circle Area (1) Enter radius, then press tab key or click on "area" box. radius (cm): <input type="text" name="radius" size="6" maxlength="7" value="-99", onblur="area.value=getArea(parseFloat(radius.value));" /> area (cm 2 ): <input type="text" name="area" size="6" maxlength="7" value="-99" /> Document 6.1
6
Passing input “by name” Document 6.2 (circle2.htm) Circle Area (2) function getArea(r) { var radius=parseFloat(r.value); return Math.PI*parseFloat(r.value)*parseFloat(r.value); } Circle Area (1) Enter radius, then press tab key or click on "area" box. radius (cm): <input type="text" name="radius" size="6" maxlength="7" value="-99",onblur = "area.value=getArea(radius);"> area (cm 2 ):
7
Passing input through a form Document 6.3 (circle3.htm) Circle Area (4) function getArea(f) { var r=parseFloat(f.radius.value); f.area.value = Math.PI*r*r; } Circle Area (3) Enter radius, then press tab key or click on "area" box. radius (cm): <input type="text" name="radius" size="6" maxlength="7" value="-99", onblur = "getArea(form);" /> area (cm 2 ): <input type="text" name="area" size="6" maxlength="7" value="-99" /> You have to know the name of the form field. Document 6.3 ( circle3.htm ) Circle Area (4) function getArea(f) { var r=parseFloat(f.radius.value); f.area.value = Math.PI*r*r; } Circle Area (3) Enter radius, then press tab key or click on "area" box. radius (cm): <input type="text" name="radius" size="6" maxlength="7" value="-99", onblur = "getArea(form);" /> area (cm 2 ): <input type="text" name="area" size="6" maxlength="7" value="-99" /> There is no return statement.
8
Returning multiple outputs with a form Document 6.4 ( circleStuff.htm ) … function circleStuff(f) { var r=parseFloat(f.radius.value); f.area.value=Math.PI*r*r; f.circumference.value=2.*Math.PI*r; }
9
Using the array… Using the elements 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 know their order and interpretation.
10
Returning Multiple Values in an Array Document 6.5 ( circleStuff2.htm ) … function circleStuff(r) { var A = Array(); A[0] = Math.PI*r*r; A[1] = 2.*Math.PI*r; return A; } … Enter radius, then press tab key or click on "area" or "circumference field. 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 2 ): circumference(cm): … You don’t have to know anything about the field names. You have to know what each array element contains.
11
Global Methods Table 6.1. (partial) Some Globa l methods for evaluating and converting strings. Global method DescriptionExample 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.
12
Using Using ParseInt() Document 6.6 ( parseIntBug.htm ) parseInt() "bug" integer value: Click for parseInt("string") result: Click for parseInt("string",10) result: Click for parseFloat("string") result:
13
Using the eval() method Document 6.7 ( calculator.htm ) Simple Calculator 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" />
14
Event Handlers Table 6.2. Summary of some event handlers used in forms. Event handler Action onblur Initiates action when a user tabs from a form field or clicks elsewhere in a document. onchange Initiates action when a user changes the contents of a form field. onclick Initiates action when a user clicks on form input field. onfocus Initiates action when a user tabs to or clicks on a form field. onload Inside a tag, initiates action when a document is loaded into the user’s browser. Table 6.2. Summary of some event handlers used in forms.
15
Recursive Functions 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 Document 6.8 (factorial2.htm) Calculate n! function nFactorial(n) { if (n Calculate n factorial (n!) Enter n (a non-negative integer): (Press Tab to get n!.)
16
Tracking recursive calls Local value of n Action Value returned n = 4Initial callDeferred n = 31 st recursive callDeferred n = 22 nd recursive callDeferred n = 13 rd recursive call1 n = 2Complete multiplication 2·12 n = 3Complete multiplication 3·26 n = 4Complete multiplication 4·624
17
Fibonacci Numbers Document 6.9 (fibonacci.htm) Calculate Fibonacci numbers function Fib(n) { if (n Calculate the n th Fibonacci number Enter n (a positive integer): (Press Tab to get n th Fibonacci number.) <input type="text" name="FibN" size="8" maxlength="8" value="1" />
18
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 n th ring from A to C. 3.Move n-1 rings from B to C.
19
Towers of Hanoi Solution Document 6.10 (towers.htm) function move(n,start,end,intermediate) { if (n > "0") { move(n-1,start,intermediate,end); document.write("move ring "+n+ " from "+start+" to "+end+". "); move(n-1,intermediate,end,start); } } var n=prompt("Give n:"); move(n,"A","C","B");
20
Pass ID Document 6.11(a) (passID.htm) Get ID and password. 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; } <form method="link" action="catchID.htm" name="login_form" onsubmit="checkIDPW();"> ID: PW:
21
Catch ID Document 6.11(b) (catchID.htm) Receive ID and password from another document. 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));
22
revisited sort() revisited Document 6.12 ( sort2.htm ) Sorting Arrays 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);
23
Dewpoint Temperature Document 6.13 (dewpoint.htm) 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.; } onclick="DP.value=getDewpoint(T,RH)" />
24
Monthly Loan Payment Document 6.14 (loan.htm) function getPayment(P,r,n) { r=r/100./12.; var M=P*r/(1.-1./Math.pow(1.+r,n)); return M.toFixed(2) } onclick= "monthly.value=getPayment(parseFloat(amount.value), parseFloat(rate.value),parseInt(n.value));"
25
Array-derived Pull-down Menus Document 6.16 (buildMenu.htm) Build a variable-length pull-down menu … Here's the menu: Click on an item to select it. <select name="stuff" size="10" onchange="listChoice.value=getSelected(stuff); "> This is the item selected: Build menu when this application loads.
26
Array-derived Pull-down Menus (concluded) 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; }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.