Javascript - 函数声明

Javascript - 函数声明 首页 / JavaScript入门教程 / 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>

Return 语句

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>

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入浅出gRPC -〔李林锋〕

深入浅出区块链 -〔陈浩〕

Nginx核心知识150讲 -〔陶辉〕

MySQL实战45讲 -〔林晓斌〕

Java性能调优实战 -〔刘超〕

浏览器工作原理与实践 -〔李兵〕

Electron开发实战 -〔邓耀龙〕

讲好故事 -〔涵柏〕

LangChain 实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)