ReactES6スプレッドオペレーター


スプレッド演算子

JavaScriptのスプレッド演算子(...)を使用すると、既存の配列またはオブジェクトのすべてまたは一部を別の配列またはオブジェクトにすばやくコピーできます。

const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];

スプレッド演算子は、多くの場合、破棄と組み合わせて使用​​されます。

からの最初と2番目の項目を変数に割り当て、numbers残りを配列に入れます。

const numbers = [1, 2, 3, 4, 5, 6];

const [one, two, ...rest] = numbers;

オブジェクトでもspread演算子を使用できます。

次の2つのオブジェクトを組み合わせます。

const myVehicle = {
  brand: 'Ford',
  model: 'Mustang',
  color: 'red'
}

const updateMyVehicle = {
  type: 'car',
  year: 2021, 
  color: 'yellow'
}

const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}

一致しなかったプロパティが結合されていることに注意してください。ただし、一致したプロパティはcolor、最後に渡されたオブジェクトによって上書きされていますupdateMyVehicle結果の色は黄色になります。


エクササイズで自分をテストする

エクササイズ:

次の配列を組み合わせるには、spread演算子を使用します。

const arrayOne = ['a', 'b', 'c'];
const arrayTwo = [1, 2, 3];
const arraysCombined = [];