【JS】箭头函数中{} 和()的区别

24 阅读1分钟

1️⃣使用{}

const f = (x) => { x * 2 };   // 返回 undefined,因为没写 return
console.log(f(3));            // 输出 undefined

const g = (x) => { return x * 2 };  // 正确写法,返回 6
console.log(g(3));                   // 输出 6

2️⃣使用()

const h = (x) => (x * 2);
console.log(h(3));   // 输出 6

总结:

  • 箭头函数 {} 包裹函数体时,需要手动写 return 才会返回值。
  • 箭头函数 () 包裹时,会隐式返回括号中的表达式。