有人可以向我解释为什么这种语法使用圆括号而不是大括号,在 reduce 方法中添加逗号而不是更多 "return" 吗?

Can someone explain to me why this syntax using parentheses instead of curly brackets, adding comma and no more "return" in reduce method?

我有一个简短的问题,我认为它与换行符或其他问题有关,但我找不到答案或 post。这是使用 reduce() 方法的示例。

这是我经常做或看到的:

const unique = ['a','b','c','a''a','a','b'];

unique.reduce((acc, val)=> {acc[val]=(acc[val]||0)+1; return acc;}, {}); //{ a: 4, b: 2, c: 1 }

不过,我们也可以使用这种语法:去掉大括号&return,改用圆括号,在acc前加一个,。谁能给我解释一下这个语法?

unique.reduce((acc, val)=> (acc[val]=(acc[val]||0)+1, acc), {}); // { a: 4, b: 2, c: 1 }


这是因为您的示例中使用了逗号运算符。来自 MDN:

The comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand.

(acc[val]=(acc[val]||0)+1, acc) 中,逗号就是这样做的,它先做左边的部分,然后 returns acc.

更新: 用花括号代替圆括号是行不通的,因为它不符合 JS 箭头函数语法。来自 MDN 上的 Arrow function 文章:

if the body requires additional lines of processing, you'll need to re-introduce brackets PLUS the "return"

所以 return 需要用大括号,而用括号是一个简洁的箭头函数,不需要 return.