函数是一组可重用的代码,可以在程序中的任何位置调用,这样就无需一次又一次编写相同的代码,它可以帮助程序员编写模块化代码。
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函数,有很多知识要学习,但是已经在本教程中介绍了最重要的概念。
JavaScript nested Function (嵌套函数)
JavaScript Function Constructors (构造函数)
JavaScript Function Literals (函数字面量)
参考链接
https://www.learnfk.com/javascript/javascript-functions.html
随时随地看视频