JavaScript函数如何定义

这篇“JavaScript函数如何定义”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“JavaScript函数如何定义”文章吧。

济源网站建设公司成都创新互联公司,济源网站设计制作,有大型网站制作公司丰富经验。已为济源上千提供企业网站建设服务。企业网站搭建\成都外贸网站建设公司要多少钱,请找那个售后服务好的济源做网站的公司定做!

功能定义

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

句法

此处显示了基本语法。


   

例子

试试下面的例子。它定义了一个名为 sayHello 的函数,它不接受任何参数


   

调用函数

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


      
      
         function sayHello() {            document.write ("Hello there!");
         }            
      
   
      

Click the following button to call the function

             
                             

Use different text in write method and then try...

   

输出

Click the following button to call the functionUse different text in write method and then try...

功能参数

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

例子

试试下面的例子。我们在这里修改了sayHello函数。现在它需要两个参数。


      
      
         function sayHello(name, age) {            document.write (name + " is " + age + " years old.");
         }            
      
   
      

Click the following button to call the function

             
                             

Use different parameters inside the function and then try...

   

输出

Click the following button to call the functionUse different parameters inside the function and then try...

声明

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

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

例子

试试下面的例子。它定义了一个函数,该函数接受两个参数并将它们连接起来,然后在调用程序中返回结果。


     
      
         function concatenate(first, last) {            var full;
            full = first + last;            return full;
         }         function secondFunction() {            var result;
            result = concatenate('Zara', 'Ali');            document.write (result );
         }            
      
   
      

Click the following button to call the function

             
                             

Use different parameters inside the function and then try...

     

输出

Click the following button to call the functionUse different parameters inside the function and then try...

以上就是关于“JavaScript函数如何定义”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注创新互联行业资讯频道。


网页题目:JavaScript函数如何定义
网页路径:http://pwwzsj.com/article/jdgipi.html