ES6の破壊に反応する
破壊
破壊を説明するために、サンドイッチを作ります。サンドイッチを作るために冷蔵庫からすべてを取り出しますか?いいえ、サンドイッチに使いたいアイテムだけを取り出します。
破壊はまったく同じです。使用している配列またはオブジェクトがある場合がありますが、必要なのはこれらに含まれるアイテムの一部だけです。
分解すると、必要なものだけを簡単に抽出できます。
配列の破壊
配列項目を変数に割り当てる古い方法は次のとおりです。
前:
const vehicles = ['mustang', 'f-150', 'expedition'];
// old way
const car = vehicles[0];
const truck = vehicles[1];
const suv = vehicles[2];
配列項目を変数に割り当てる新しい方法は次のとおりです。
破壊する場合:
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car, truck, suv] = vehicles;
配列を破棄するときは、変数が宣言される順序が重要です。
車とSUVだけが必要な場合は、トラックを省略してコンマを保持することができます。
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car,, suv] = vehicles;
関数が配列を返す場合、破棄は便利です。
例
function calculate(a, b) {
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = a / b;
return [add, subtract, multiply, divide];
}
const [add, subtract, multiply, divide] = calculate(4, 7);
オブジェクトを破壊する
関数内でオブジェクトを使用する古い方法は次のとおりです。
前:
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
}
myVehicle(vehicleOne);
// old way
function myVehicle(vehicle) {
const message = 'My ' + vehicle.type + ' is a ' + vehicle.color + ' ' + vehicle.brand + ' ' + vehicle.model + '.';
}
関数内でオブジェクトを使用する新しい方法は次のとおりです。
破壊する場合:
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
}
myVehicle(vehicleOne);
function myVehicle({type, color, brand, model}) {
const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';
}
オブジェクトのプロパティを特定の順序で宣言する必要がないことに注意してください。
ネストされたオブジェクトを参照し、コロンと中括弧を使用してネストされたオブジェクトから必要なアイテムを再度非構造化することで、深くネストされたオブジェクトを非構造化することもできます。
例
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red',
registration: {
city: 'Houston',
state: 'Texas',
country: 'USA'
}
}
myVehicle(vehicleOne)
function myVehicle({ model, registration: { state } }) {
const message = 'My ' + model + ' is registered in ' + state + '.';
}