Java脚本定义和调用函数示例

什么是函数 Java脚本?

函数在任何编程语言中都非常重要且有用,因为它们使代码可重复使用。函数是一段代码,只有调用时才会执行。如果您有几行代码需要多次使用,您可以创建一个包含重复代码行的函数,然后在需要的地方调用该函数。

如何在 Java脚本

  1. 使用关键字 function 后跟函数的名称。
  2. 在函数名称之后,打开和关闭括号。
  3. 括号后,打开和关闭花括号。
  4. 在花括号内,写下你的代码行。

语法:

function functionname()
{

  lines of code to be executed

}

自己尝试一下:

<html>
<head>
	<title>Functions!!!</title>
	<script type="text/javascript">
      function myFunction()
      {
      	document.write("This is a simple function.<br />");
      }
		myFunction();
	</script>
</head>
<body>
</body>
</html>

带参数的函数

您也可以创建带有参数的函数。参数应在括号内指定

语法:

function functionname(arg1, arg2)

{

  lines of code to be executed

}

自己尝试一下:

<html>
<head>
	<script type="text/javascript">
		var count = 0;
		function countVowels(name)
		{
			for (var i=0;i<name.length;i++)
			{
              if(name[i] == "a" || name[i] == "e" || name[i] == "i" || name[i] == "o" || name[i] == "u")
              count = count + 1;
			}
		document.write("Hello " + name + "!!! Your name has " + count + " vowels.");
		}
   	 	var myName = prompt("Please enter your name");
    	countVowels(myName);
	</script>
</head>
<body>
</body>
</html>

Java脚本返回值

您还可以创建返回值的 JS 函数。在函数内部,您需要使用关键字 回报 后面跟着要返回的值。

语法:

function functionname(arg1, arg2)

{

  lines of code to be executed

  return val1;

}

自己尝试一下:

<html>
<head>
	<script type="text/javascript">
		function returnSum(first, second)
        {
          var sum = first + second;
          return sum;
        }
      var firstNo = 78;
      var secondNo = 22;
      document.write(firstNo + " + " + secondNo + " = " + returnSum(firstNo,secondNo));
	</script>
</head>
<body>
</body>
</html>