JavaScript - 函数
JavaScript 中的函数是一组可重用的代码,可以在程序的任何位置调用。它消除了重复编写相同代码的需要。它帮助程序员编写模块化代码。函数允许程序员将大型程序拆分成多个易于管理的小函数。
与任何其他高级编程语言一样,JavaScript 也支持使用函数编写模块化代码所需的所有功能。您一定在前面的章节中见过alert()和write()之类的函数。我们反复使用这些函数,但它们在 JavaScript 核心中只被编写过一次。
JavaScript 也允许我们编写自己的函数。本节介绍如何在 JavaScript 中编写自己的函数。
函数定义
在使用函数之前,我们需要对其进行定义。在 JavaScript 中定义函数的最常见方式是使用 function 关键字,后跟唯一的函数名称、参数列表(可能为空)以及用花括号括起来的语句块。
函数调用时需要执行的所有语句都必须写在花括号内。
语法
在 JavaScript 中定义函数的基本语法如下:
function functionName(parameter-list) {
statements
}
这种函数定义称为函数声明或函数语句。我们也可以使用函数表达式来定义函数。我们将在下一章详细讨论函数表达式。
以下示例定义了一个名为 sayHello 的函数,它不接受任何参数 -
function sayHello() {
alert("Hello there");
}
函数表达式
JavaScript 中的函数表达式允许您将函数定义为表达式。函数表达式类似于匿名函数声明。函数表达式可以赋值给变量。
JavaScript 中函数表达式的语法如下
const varName = function (parameter-list) {
statements
};
在下面的示例中,我们使用函数表达式定义了一个 JavaScript 函数,并将其赋值给一个变量名 myFunc。
const myFunc = function (x, y){
return x + y;
};
调用函数
要在脚本的后续位置调用函数,只需将该函数的名称用括号 () 括起来,如以下代码所示。
示例
以下代码在输出中显示了按钮。点击按钮时,它将执行 sayHello() 函数。sayHello() 函数会在输出中打印"Hello there!"消息。
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("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 the 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 语句。如果您想从函数中返回一个值,则必须使用 return 语句。该语句应位于函数的最后一个语句中。
例如,您可以在函数中传递两个数字,然后函数会在调用程序中返回它们的乘积。
示例
以下代码定义了一个函数,该函数在调用程序中返回结果之前,会连接两个参数。您也可以查看如何使用 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');
alert(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 被称为"一等函数"。函数可以作为参数传递给其他函数。
示例
在下面的示例中,我们使用函数表达式声明了一个函数,并使用该函数与其他字符串连接。
<html>
<body>
<div id = "output"> </div>
<script>
const myFunc = function (){ return "Hello ";};
document.getElementById("output").innerHTML = myFunc() + "Users.";
</script>
</body>
</html>
我们在不同的章节中介绍了两个重要概念。

