箭头功能可以用很多不同的方式编写,有没有什么方法可以更正确"?
let fun1 = (a) => { return a; }
let fun2 = a => a;
就像上面那些情况一样,fun2比fun1快吗?它们之间的区别是什么?
答案 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
可以省略,如果它适合一行正如您所看到的,所有这些都是箭头函数的有效语法,它们都不比另一个快,您使用哪一个取决于您编码的方式。