簡體   English   中英

什么是正確的箭頭函數語法?

[英]What is the correct arrow function syntax?

箭頭函數可以用很多不同的方式編寫,有沒有“更正確”的方式?

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;
}

所以我們有一些規則:

  • 當函數沒有或超過一個參數時,需要在參數周圍加上括號,如果只有一個,括號可以省略。
  • 如果函數只有 return 大括號和關鍵字return可以省略,如果它適合一行
  • 如果函數有多於一行或沒有返回,則需要大括號。

如您所見,所有這些都是箭頭函數的有效語法,它們中沒有一個比另一個更快,您使用哪一個取決於您的編碼方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM