【问题标题】:What is the correct arrow function syntax?什么是正确的箭头函数语法?
【发布时间】:2018-05-15 14:55:21
【问题描述】:

箭头函数可以写成很多不同的方式,有没有“更正确”的方式?

let fun1 = (a) => { return a; }
let fun2 = a => a;

就像上面的例子,fun2 比 fun1 快吗?它们有什么区别?

【问题讨论】:

标签: javascript arrow-functions


【解决方案1】:

箭头函数可以用不同的方式编写,如下所示:

// No params, just returns a string
const noParamsOnlyRet = () => 'lul';

// No params, no return
const noParamsNoRet = () => { console.log('lul'); };

// One param, it retuns what recives
const oneParamOnlyRet = a => a;

// Makes the same thing that the one above
const oneParamOnlyRet2 = a => { return a; };

// Makes the same thing that the one above
const oneParamOnlyRet3 = (a) => a; 

/* Makes the same thing that the one above, parentheses in return are optional,
 * only needed if the return have more then one line, highly recomended put 
 * objects into parentheses.
*/
const oneParamOnlyRet4 = (a) => (a);  

// Mult params, it returns the sum
const multParamsOnlyRet = (a, b) => a + b; 

// Makes the same thing that the one above
const multParamsOnlyRet2 = (a, b) => { return a + b; }

// Curly brackets are needed in multiple line arrow functions
const multParamsMultLines = (a, b) => { 
    let c = a + b;
    return c;
}

所以我们有一些规则:

  • 当函数没有或超过一个参数时,需要在参数周围加上括号,如果只有一个,括号可以省略。
  • 如果函数只有一个 return 大括号和关键字 return 可以省略,如果它适合一行
  • 如果函数多行或没有返回值,则需要大括号。

如您所见,所有这些都是箭头函数的有效语法,没有一个比另一个更快,您使用哪一个取决于您的编码方式。

【讨论】:

  • 这条线根本不重要。
  • “和上面那个一样”不是英文的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 2021-02-11
  • 2018-10-31
  • 2014-01-20
  • 2020-04-21
  • 1970-01-01
相关资源
最近更新 更多