【问题标题】:About semicolon in ES6 when using return关于 ES6 中使用 return 时的分号
【发布时间】:2018-10-30 18:47:26
【问题描述】:

我是 JS 新手。如果我添加这样的分号${this.name} is friends with ${el};我会收到一个错误“参数列表后未捕获的语法错误:缺少)”。我可以知道为什么吗?由于在 ES5 中,我可以使用分号,例如 return this.name + ' is friends with ' +el; 非常感谢!

function Person(name) {
    this.name = name;
}

ES6
Person.prototype.myFriends5 = function(friends) {
var arr = friends.map((el) =>
     `${this.name} is friends with ${el}`
);
console.log(arr);
}
var friends = ['Bob', 'Jane', 'Mark'];
new Person('John').myFriends5(friends);

【问题讨论】:

    标签: javascript ecmascript-6 arrow-functions


    【解决方案1】:

    箭头函数有两种写法:

    (params) => expression
    

    (params) => {
        body
    }
    

    其中body 就像传统函数的主体(一系列语句)。

    当您使用第一种格式时,您不能有;,因为这在表达式中无效,它用于终止函数体中的语句。这和你不能写的原因是一样的:

    console.log(a;)
    

    第一种形式是:

    (params) => {
        return expression;
    }
    

    关于什么是有效表达式的经验法则是,它可以放在括号内。所以如果你可以写这样的东西:

    a = (something)
    

    那么你可以写:

    (params) => something
    

    因为你不会写:

    a = (`${this.name} is friends with ${el}`;)
    

    你不能写:

    (params) => `${this.name} is friends with ${el}`;
    

    【讨论】:

    • 啊,我可以知道在 (params) => 表达式中,这个表达式是否总是意味着“返回一些东西”?如果我写类似 (params) => let i = 10 的东西,是否意味着:(params) => { return let i = 10; } ?非常感谢!
    • 是的,总是这样。因为let 是一个语句,而不是一个表达式,所以它不起作用。
    • 基本上,如果你不会写(blah)你就不能写=> blah
    • 非常感谢!所以我可以写 (params) => i = 10 和 (params) => { return i = 10; } 对?它会首先将 10 分配给 i 然后返回 i 即 10?
    • 是的,你可以这样做。它将分配给在外部范围中声明的变量。
    猜你喜欢
    • 2016-04-29
    • 1970-01-01
    • 2015-12-24
    • 2017-06-07
    • 2022-01-19
    相关资源
    最近更新 更多