简体   繁体   English

有人可以向我解释为什么这种语法使用括号而不是大括号,添加逗号并且在 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?

I have a quick question, which I think related to line break or something, but I could not find an answer or post about.我有一个快速的问题,我认为这与换行符或其他东西有关,但我找不到答案或发布。 Here's an example using reduce() method.这是一个使用reduce()方法的示例。

This is what I usually do or see:这是我通常做或看到的:

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 }

However, we can also use this syntax: remove the curly brackets & return , use parentheses instead and add a , before acc .但是,我们也可以使用这种语法:删除大括号 & return ,改用括号并在acc之前添加一个, Can someone explain to me this syntax?有人可以向我解释这种语法吗?

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


This is because comma operator is used in your example.这是因为您的示例中使用了逗号运算符。 From MDN:来自MDN:

The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand.逗号运算符( , ) 计算其每个操作数(从左到右)并返回最后一个操作数的值。

In (acc[val]=(acc[val]||0)+1, acc) comma does exactly that, it does left part first then returns acc .(acc[val]=(acc[val]||0)+1, acc)中,逗号正是这样做的,它首先执行 left 部分然后返回acc

Update: Replacing parentheses with curly brackets will not work, because it doesn't comply with JS arrow function syntax.更新:用大括号替换括号将不起作用,因为它不符合 JS 箭头 function 语法。 From Arrow function article on MDN:来自 MDN 上的Arrow function文章:

if the body requires additional lines of processing, you'll need to re-introduce brackets PLUS the "return"如果正文需要额外的处理线,您需要重新引入括号加上“返回”

so return is required with curly brackets, while with parentheses it's a concise arrow function which doesn't need return .所以return需要大括号,而括号是一个简洁的箭头 function ,不需要return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM