正确的箭头函数语法是什么?
What is the correct arrow function syntax?
箭头函数可以有很多种写法,有什么写法"more correct"?
let fun1 = (a) => { return a; }
let fun2 = a => a;
就像上面那些情况一样,fun2 比 fun1 快吗?它们有什么区别?
箭头函数可以用一些不同的方式编写,如下所示:
// 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;
}
所以我们有一些规则:
- 当函数有none个或多个参数时,参数两边需要括号,如果只有一个,括号可以省略。
- 如果函数只有一个 return 大括号和关键字
return
可以省略,如果它适合一行
- 如果函数不止一行或没有return.
,则需要大括号
如您所见,所有这些都是箭头函数的有效语法,其中 none 个比另一个更快,您使用哪个取决于您的编码方式。
箭头函数可以有很多种写法,有什么写法"more correct"?
let fun1 = (a) => { return a; }
let fun2 = a => a;
就像上面那些情况一样,fun2 比 fun1 快吗?它们有什么区别?
箭头函数可以用一些不同的方式编写,如下所示:
// 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;
}
所以我们有一些规则:
- 当函数有none个或多个参数时,参数两边需要括号,如果只有一个,括号可以省略。
- 如果函数只有一个 return 大括号和关键字
return
可以省略,如果它适合一行 - 如果函数不止一行或没有return. ,则需要大括号
如您所见,所有这些都是箭头函数的有效语法,其中 none 个比另一个更快,您使用哪个取决于您的编码方式。