JavaScript - 函数

一个函数是一组可重用的代码,可以在程序的任何地方调用。这消除了一次又一次地编写相同代码的需要。它可以帮助程序员编写模块化代码。函数允许程序员将大程序划分为许多小而易于管理的函数。

与任何其他高级编程语言一样,JavaScript也支持使用函数编写模块化代码所需的所有功能。您必须在前面的章节中看到过 alert() write()等功能。我们一次又一次地使用这些函数,但它们只用核心JavaScript编写过一次。

JavaScript允许我们编写自己的函数。本节介绍如何使用JavaScript编写自己的函数。

函数定义

在使用函数之前,我们需要定义它。在JavaScript中定义函数的最常用方法是使用 function 关键字,后跟唯一的函数名,参数列表(可能为空),以及由大括号括起来的语句块。

语法

此处显示基本语法。

<script type = "text/javascript">
   <!--
      function functionname(parameter-list) {
         statements
      }
   //-->
</script>


示例

请尝试以下示例。它定义了一个名为sayHello的函数,它不带参数 :

<script type = "text/javascript">
   <!--
      function sayHello() {
         alert("Hello there");
      }
   //-->
</script>


调用函数

要在脚本的某个地方调用函数,只需要编写名称该函数如下面的代码所示。

在线演示

<html>
   <head>   
      <script type = "text/javascript">
         function sayHello() {
            document.write ("Hello there!");
         }
      </script>
      
   </head>
   
   <body>
      <p>Click the following button to call the function</p>      
      <form>
         <input type = "button" onclick = "sayHello()" value = "Say Hello">
      </form>      
      <p>Use different text in write method and then try...</p>
   </body>
</html>

功能参数

到目前为止,我们已经看到了没有参数的函数。 但是在调用函数时有一个传递不同参数的工具。 可以在函数内捕获这些传递的参数,并且可以对这些参数进行任何操作。 函数可以使用逗号分隔的多个参数。

示例

请尝试以下示例。 我们在这里修改了sayHello函数。 现在需要两个参数。

在线演示

<html>
   <head>   
      <script type = "text/javascript">
         function sayHello(name, age) {
            document.write (name + " is " + age + " years old.");
         }
      </script>      
   </head>
   
   <body>
      <p>Click the following button to call the function</p>      
      <form>
         <input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
      </form>      
      <p>Use different parameters inside the function and then try...</p>
   </body>
</html>

返回声明

JavaScript函数可以有一个可选的return语句。 如果要从函数返回值,则必须执行此操作。 该语句应该是函数中的最后一个语句。

例如,您可以在函数中传递两个数字,然后您可以期望该函数在您的调用程序中返回它们的乘法。

示例

请尝试以下示例。 它定义了一个函数,它接受两个参数并在调用程序中返回结果之前将它们连接起来。

在线演示

<html>
   <head>  
      <script type = "text/javascript">
         function concatenate(first, last) {
            var full;
            full = first + last;
            return full;
         }
         function secondFunction() {
            var result;
            result = concatenate('Zara', 'Ali');
            document.write (result );
         }
      </script>      
   </head>
   
   <body>
      <p>Click the following button to call the function</p>      
      <form>
         <input type = "button" onclick = "secondFunction()" value = "Call Function">
      </form>      
      <p>Use different parameters inside the function and then try...</p>  
  </body>
</html>