在单箭头(auto return)函数中添加控制台日志而不添加大括号

Add console log in an one arrow (auto return) function without adding curly braces

所以考虑你有一个单行自动 return 箭头函数:

const test = (val) => val;

如果不执行以下操作,您将如何检查 val

const test = (val) => {
  console.log(val);
  return val;
};

您实际上可以在箭头函数和返回值之间使用 ||,如下所示:

const test = (val) => console.log(val) || val;

这不会干扰进程,并且还会记录 val,而无需添加 {}return 并在完成后撤消它

echo 是一个很棒的函数 -

const echo = (x) =>
  ( console.log(x)
  , x
  )

const test = x => echo(x) + 1

const arr = [ 1, 2, 3 ]

const result = arr.map(test)

console.log(result)

箭头函数是一种函数式风格。使用函数式技术将使使用箭头表达式变得更加愉快 -

const effect = f => x =>
  (f(x), x)
  
const echo =
 effect(console.log)
  
const test = x => echo(x + 1) // <-- wrap echo around anything

const arr = [ 1, 2, 3 ]

const result = arr.map(test)

console.log(result)

// 2
// 3
// 4
// [ 2, 3, 4 ]

可以用echof包裹整个函数,比如echof(test)-

const effect = f => x =>
  (f(x), x)

const comp = (f, g) =>
  x => f(g(x))

const echo =
 effect(console.log)

const echof = f =>
  comp(echo, f)

const test = x => x * x

const arr = [ 1, 2, 3 ]

const result = arr.map(echof(test)) // <-- echof

console.log(result)
// 1
// 4
// 9
// [ 1, 4, 9 ]