JavaScript ( Arrow Function) 介绍

2 阅读1分钟

JavaScript 箭头函数 (Arrow Function),是 ES6 引入的一种更简洁的函数定义方式,本质上是匿名函数的语法糖,有一些独特的特性, 其核心是用 => 替代传统函数的 function 关键字:

场景传统函数写法箭头函数写法
无参数function() { ... }() => { ... }
单个参数function(x) { ... }x => { ... }(括号可省略)
多个参数function(x, y) { ... }(x, y) => { ... }
单行返回(无大括号)function(x) { return x*2 }x => x*2(自动返回,无需 return)

案例:

// 1. 无参数的箭头函数

const sayBye=()=>{ console.log("Bye!");};

sayBye(); // 输出: Bye!

// 2. 单个参数的箭头函数(省略括号)

const amount=num=> num *2;

console.log(amount(5)); // 输出: 10

// 3. 多个参数的箭头函数

const calc=(a, b)=> a + b;

console.log(calc(5,4)); // 输出:9

// 4. 多行逻辑的箭头函数(必须用大括号,且需手动return)

const calculate=(x, y)=>{const sum = x + y;

const product = x * y;

return sum + product; // 多行必须显式return};

console.log(calculate(2,3)); // 输出: 2+3 + 2*3 = 11