目录

Javascript - Functions

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

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

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

函数定义 (Function Definition)

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

语法 (Syntax)

这里显示了基本语法。

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

例子 (Example)

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

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

调用一个函数 (Calling a Function)

要在稍后的脚本中调用函数,您只需要编写该函数的名称,如以下代码所示。

<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>

输出 (Output)

新页面打开

功能参数

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

例子 (Example)

请尝试以下示例。 我们在这里修改了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>

输出 (Output)

新页面打开

return 语句

JavaScript函数可以有一个可选的return语句。 如果要从函数返回值,则需要这样做。 该语句应该是函数中的最后一个语句。

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

例子 (Example)

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

<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>

输出 (Output)

新页面打开

有很多关于JavaScript函数的知识,但是我们已经介绍了本教程中最重要的概念。

↑回到顶部↑
WIKI教程 @2018