【问题标题】:Using curly braces in an array reduce function? [duplicate]在数组减少函数中使用花括号? [复制]
【发布时间】: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


【解决方案1】:

当运行时发现大括号被省略时,它会为您包含return 语句。请参阅下面的示例,以及Arrow functions on MDN:

(param1, param2, …, paramN) => { statements } 
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; } 

注意采用表达式的形式采用语句的形式的等价性。除非以适当的return 结尾,否则接受语句的表单将始终导致未定义的返回值。

JavaScript 没有“隐式语句块值”;在排除对象文字的情况下,{} 大括号总是引入 some 形式的非表达式。

看这个例子:

es6 console

这里是为不耐烦的人准备的:

    "use strict";

    var fn2 = function fn2(totalUpvotes, currentPost) {
      return totalUpvotes + currentPost.upVotes;
    };

    var fn3 = function fn3(totalUpvotes, currentPost) {
      totalUpvotes + currentPost.upVotes;
    };

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 2014-07-27
    • 2020-06-21
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多