JavaScript 中的胖箭头函数与简洁箭头函数
javascriptweb developmentobject oriented programming更新于 2025/8/27 6:04:17
简洁箭头函数是单行函数的更精简形式的胖箭头函数。如果函数体只有一行代码,则函数体不需要花括号 {},因为简洁箭头函数具有隐式返回。此外,如果只有一个参数,则可以不用括号 () 来编写,但如果没有参数,则必须使用括号。
语法
胖箭头函数 −
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">点击此处</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>
输出

点击‘CLICK HERE’按钮 −

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

