代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>箭头函数</title>
<script src="../file/jquery-3.7.0.js"></script>
</head>
<!-- 使用箭头函数语法: (形参表)=>{函数体}-->
<body>
<button>无参且方法体只有一条语句触发按钮</button><br />
<button>无参且方法体有多条语句触发按钮</button>
<script>
//若方法的参数表中没有参数则用()=>{方法体};若方法体只有一条语句则可以省略大括号省略大括号后面的分号必须省略
$("button:eq(0)").click(() =>
console.log("这是无参且方法体只有一条语句触发按钮")
);
//方法体中有多条语句时方法体的大括号不可以省略
$("button:eq(1)").click(() => {
var arr = [100, "hello", "你好"];
//有一个参数且方法体只有一条语句,可以将形参列表的括号省略不写
arr.forEach((e) =>
console.log(`这是无参且方法体有多条语句触发按钮,遍历数组元素为:${e}`)
);
});
console.log("------方法体中只有一条语句而且是返回语句(return)时------");
//方法体中只有一条语句而且是返回语句时return可以省略不写
var xxx = (a) => a * a; //相当于 var xxx = function(a){return a*a}
var xx = xxx(9);
console.log(`xx的值为${xx}`);
</script>
</body>
</html>
效果: