更新时间:2021-11-29 12:48:44 来源:动力节点 浏览852次
函数是一组可重用的代码,可以在程序的任何地方调用。这消除了一次又一次编写相同代码的需要。它帮助程序员编写模块化代码。函数允许程序员将一个大程序划分为许多小的和可管理的函数。
与任何其他高级编程语言一样,JavaScript 也支持使用函数编写模块化代码所需的所有功能。您一定在前面的章节中看到了alert()和write() 之类的函数。我们一次又一次地使用这些函数,但它们只用核心 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>
输出
Click the following button to call the function
Use different text in write method and then try...
到目前为止,我们已经看到了没有参数的函数。但是有一个工具可以在调用函数时传递不同的参数。这些传递的参数可以在函数内部捕获,并且可以对这些参数进行任何操作。一个函数可以接受多个用逗号分隔的参数。
试试下面的例子。我们在这里修改了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>
输出
Click the following button to call the function
Use different parameters inside the function and then try...
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>
输出
Click the following button to call the function
Use different parameters inside the function and then try...
通过上述相信大家对JavaScript函数的定义已经有所了解,如果您想了解更多相关知识,不妨来关注一下动力节点的Java在线学习,里面的课程内容详细,由浅到深,适合小白学习,希望对大家能够有所帮助。
0基础 0学费 15天面授
有基础 直达就业
业余时间 高薪转行
工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习