什么是正确的箭头函数语法?

时间:2018-05-15 14:55:21

标签: javascript arrow-functions

箭头功能可以用很多不同的方式编写,有没有什么方法可以更正确"?

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

就像上面那些情况一样,fun2比fun1快吗?它们之间的区别是什么?

1 个答案:

答案 0 :(得分:0)

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

// 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可以省略,如果它适合一行
  • 如果函数有多行或者没有返回,则需要使用大括号。

正如您所看到的,所有这些都是箭头函数的有效语法,它们都不比另一个快,您使用哪一个取决于您编码的方式。

相关问题