JavaScript 中的粗箭頭函式與精簡箭頭函式
簡潔的箭頭函式對於單行函式來說是一種更加直線型的粗箭頭函式形式。如果函式主體只有一行程式碼,那麼就不需要使用大括號 {} 表示函式主體,因為簡潔的箭頭函式具有隱式返回功能。此外,如果只有一個引數,那麼可以不帶括號 () 來編寫,但如果沒有引數,則需要括號。
語法
粗箭頭函式 −
let add = (a,b) =>{return a+b;}簡潔的箭頭函式
let add = (a,b)=>a+b;
如果只有一個引數 −
let add = a=>a+22;
以下是 JavaScript 中粗箭頭函式與簡潔箭頭函式的程式碼 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Fat vs concise arrow functions</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to call the add() and multiply() arrow function</h3>
<script>
let resEle = document.querySelector(".result");
let add = (a, b) => a + b;
let multiply = (a, b) => {
return a * b;
};
document.querySelector(".Btn").addEventListener("click", () => {
resEle.innerHTML = "Sum of 32 and 19 = " + add(32, 19) + "<br>";
resEle.innerHTML =
"Multiplication of 32 and 19 = " + multiply(32, 19) + "<br>";
});
</script>
</body>
</html>輸出

單擊“點選此處”按鈕 −

廣告
資料結構
網路技術
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP