这篇“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 functionUse 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 functionUse 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 functionUse different parameters inside the function and then try...
以上就是关于“JavaScript函数如何定义”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注天达云行业资讯频道。