【发布时间】:2018-07-24 11:09:15
【问题描述】:
如果fn3 被替换为fn2 在此示例中运行在节点 9.5.0 中,console.log(totalUpvotes) 将记录 undefined。 IIUC的结果应该是一样的(92)?
const posts = [{id: 1, upVotes: 2}, {id:2, upVotes: 89}, {id: 3, upVotes: 1}];
const fn2 = (totalUpvotes, currentPost) => totalUpvotes + currentPost.upVotes;
const fn3 = (totalUpvotes, currentPost) => {totalUpvotes + currentPost.upVotes}
const totalUpvotes = posts.reduce(fn2, 0);
console.log(totalUpvotes);
【问题讨论】:
-
{...}就像拥有一个普通函数没有return。 -
@georg 为什么会这样?
{...}有值吗?或者这是一个特殊的语法规则(或绕过一个语法规则)? -
这不是一个严格的重复.. OP 没有尝试从文字中返回一个 object 。但是,解释是相关的。
-
(x, y) => expr等价于(x, y) => { return expr; }。 -
"两个函数 (fn2, fn3) 在 es6 控制台上编译成相同的东西" - 不,再看一遍,一个有
return,另一个没有。
标签: javascript node.js lambda ecmascript-6 arrow-functions