JavaScript Tutorial/Function/Function Parameters
Содержание
Pass an array to a function
<source lang="javascript">
<HTML>
<HEAD> <TITLE> Iteration Two </TITLE> <SCRIPT> function makeArray() { var myArray = new Array(4); myArray[0] = "A"; myArray[1] = "B"; myArray[2] = "C"; myArray[3] = "D"; return myArray; } function showArray(theArray){ var quote = ""; for (var i = 0; i < theArray.length; i++){ quote += theArray[i] + " "; } return quote; } </SCRIPT> </HEAD> <BODY>
<SCRIPT> var x = makeArray(); document.write(showArray(x)); </SCRIPT>
</BODY>
</HTML></source>
Pass Form value to a function
<source lang="javascript">
<HTML> <HEAD>
<TITLE> Add three numbers </TITLE> <SCRIPT> function addThreeNums (inOne, inTwo, inThree) { var inOne = Number(inOne); var inTwo = Number(inTwo); var inThree = Number(inThree); return Number(inOne + inTwo + inThree); } </SCRIPT>
</HEAD> <BODY> <FORM Name="theForm"> <INPUT Type=Text Name="num1"> <INPUT Type=Text Name="num2"> <INPUT Type=Text Name="num3"> <INPUT Type=Button Value="Add Them" onClick="document.write("sum:" +addThreeNums(theForm.num1.value,theForm.num2.value,theForm.num3.value));"> </FORM> </BODY> </HTML></source>
Pass integer to function
<source lang="javascript">
<html> <head> <script language="JavaScript" type = "text/javascript">
</script> <title>Keyboard Event</title> </head> <body> <form name="form1">
Name: <input type = "text" name = "text1" onFocus="DisplayMsg(1)" size="20">Phone: <input type = "text" name = "text2" onFocus="DisplayMsg(2)" size="20">
</form> </body> </html></source>
Pass number to a function
<source lang="javascript">
<html> <head> <title>A Simple Page</title> <script language="JavaScript">
</script> </head> <body onLoad="calcAvg();"> </body> </html></source>
Pass value to a function
<source lang="javascript">
<html> <head> <title>A Simple Page</title> <script language="JavaScript">
</script> </head> <body>
Click <input type="button" value="AAA" onClick="yourMessage("AAA")"> for a message!
Click <input type="button" value="BBB" onClick="yourMessage("BBB")"> for another message!
</body> </html></source>
Use functionName.arguments to reference the arguments
<source lang="javascript">
<HTML> <HEAD>
<TITLE> Add all of the numbers </TITLE> <SCRIPT> function addNums () { var theAnswer = 0; for (var i = 0; i < addNums.arguments.length; i++) { var theNum = Number(addNums.arguments[i]); theAnswer += theNum; } return theAnswer; } </SCRIPT>
</HEAD> <BODY> <FORM Name="theForm"> <INPUT Type=Text Name="num1"> <INPUT Type=Text Name="num2"> <INPUT Type=Text Name="num3"> <INPUT Type=Text Name="num4"> <INPUT Type=Button Value="Add Them" onClick="document.write(addNums(theForm.num1.value,theForm.num2.value,theForm.num3.value,theForm.num4.value));"> </FORM> </BODY> </HTML></source>