更新時間:2021-11-29 12:48:44 來源:動力節點 瀏覽927次
函數是一組可重用的代碼,可以在程序的任何地方調用。這消除了一次又一次編寫相同代碼的需要。它幫助程序員編寫模塊化代碼。函數允許程序員將一個大程序劃分為許多小的和可管理的函數。
與任何其他高級編程語言一樣,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年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習