2016-06-20 17 views
5

私は5つのオブジェクトを返す関数を持っています。constとそのうちの1つをletを使って4つ宣言したいと思います。私が望んでいた場合は、すべてのオブジェクトは、私が何ができるconstを使用して宣言:複数の変数タイプを持つES6の構造化代入

const { thing1, thing2, thing3, thing4, thing5 } = yield getResults(); 

私の現在の回避策は次のとおりです。

const results = yield getResults(); 

const thing1 = results.thing1; 
const thing2 = results.thing2; 
const thing3 = results.thing3; 
const thing4 = results.thing4; 

let thing5 = results.thing5; 

しかし、分割代入は、あなたがよりエレガントにこれを行うことができます場合、私は思ったんだけど。

この問題については、MDNには記載されていません。

+3

よく 'const {thing1、...} = results;を実行してください。 let {thing5} = results; '? – Bergi

答えて

6

letconstの両方の変数を同時に初期化する構造体を実行することはできません。しかしconstへの割り当ては他のdestructureに減少させることができます。

const results = yield getResults() 

const { thing1, thing2, thing3, thing4 } = results 

let thing5 = results.thing5 
6

あなたはまだ個別に構造化代入を使用することができます

const results = yield getResults(); 
const { thing1, thing2, thing3, thing4} = results; 
let { thing5 } = results; 

また、

let thing5; 
const { thing1, thing2, thing3, thing4 } = { thing5 } = yield getResults(); 

を行うことが可能ですが、私は推測しますあなたのコードのWTF /分を減らすのではなく、むしろ避けてください。

+0

私はWTF /分のコメントは少し厳しいと思います。私は、 'const'は偶発的な間違いやコードの匂いを減らすためのかなり正当な方法だと感じています。ここに本当に可変変数が必要なものがあれば、「すべての変数を作る」というのはこれを扱う鈍器的な方法です。私はあなたの問題を見ています...私は問題を完全に避けるためにこれを書いているかもしれませんが、ここでdevは可能な限りconstを使うことが賢明です。 –

+0

@EthanBrown:スタイルガイドでは、ネストされた課題の構造化を正当な理由で禁止するつもりはありませんでした。 – Bergi

関連する問題