191

新しいES6 アロー関数returnは、いくつかの状況では暗黙的であると言います:

式は、その関数の暗黙の戻り値でもあります。

returnどのような場合に ES6 アロー関数を使用する必要がありますか?

4

6 に答える 6

305

ジャクソンは、同様の質問でこれに部分的に答えています。

ブロックがない場合のみ、暗黙的に戻ります。

  • ワンライナーが複数行に展開され、プログラマーがreturn.
  • 暗黙的なリターンは構文的にあいまいです。(name) => {id: name}オブジェクトを返します{id: name}...そうですか?違う。返しますundefined。これらの中括弧は明示的なブロックです。id:はラベルです。

これにブロックの定義を追加します。

ブロック ステートメント (または他の言語では複合ステートメント) は、0 個以上のステートメントをグループ化するために使用されます。ブロックは、一対の中かっこで区切られます。

:

// returns: undefined
// explanation: an empty block with an implicit return
((name) => {})() 

// returns: 'Hi Jess'
// explanation: no block means implicit return
((name) => 'Hi ' + name)('Jess')

// returns: undefined
// explanation: explicit return required inside block, but is missing.
((name) => {'Hi ' + name})('Jess')

// returns: 'Hi Jess'
// explanation: explicit return in block exists
((name) => {return 'Hi ' + name})('Jess') 

// returns: undefined
// explanation: a block containing a single label. No explicit return.
// more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
((name) => {id: name})('Jess') 

// returns: {id: 'Jess'}
// explanation: implicit return of expression ( ) which evaluates to an object
((name) => ({id: name}))('Jess') 

// returns: {id: 'Jess'}
// explanation: explicit return inside block returns object
((name) => {return {id: name}})('Jess') 
于 2015-03-05T22:56:42.180 に答える