[英]Add console log in an one arrow (auto return) function without adding curly braces
所以考慮你有一個單行自動返回箭頭 function:
const test = (val) => val;
如果不執行以下操作,您將如何檢查val
:
const test = (val) => {
console.log(val);
return val;
};
您實際上可以使用||
在箭頭 function 和返回值之間,如下所示:
const test = (val) => console.log(val) || val;
這不會干擾該過程,並且還會記錄val
而無需添加{}
並在完成后return
並撤消它
echo
是一個很棒的 function -
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
來包裹整個function,比如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 ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.