ES6 Destruktivlashtirish

React ES6

React ES6 Destruktivlashtirish

Destruktivlashtirish

Destruktivlashtirishni tushuntirish uchun sendvich tayyorlaymiz. Sendvich tayyorlash uchun siz muzlatgichdan hamma narsani chiqarasizmi? Yo‘q, faqat kerakli narsalarni olasiz.

Destruktivlashtirish aynan shunday ishlaydi. Bizda bir massiv yoki obyekt bo‘lishi mumkin, lekin biz faqat kerakli elementlarni olishimiz mumkin.

Destruktivlashtirish faqat kerakli narsalarni ajratib olishni osonlashtiradi.

Massivlarni Destruktivlashtirish Massiv elementlarini o‘zgaruvchiga tayinlashning eski usuli:

Misol Oldingi usul:

const vehicles = ['mustang', 'f-150', 'expedition'];
 
// eski usul
const car = vehicles[0];
const truck = vehicles[1];
const suv = vehicles[2];

Yangi usul, destruktivlashtirish bilan:

Misol Destruktivlashtirish bilan:

const vehicles = ['mustang', 'f-150', 'expedition'];
 
const [car, truck, suv] = vehicles;

Massivlarni destruktivlashtirishda, o‘zgaruvchilarni e'lon qilish tartibi muhimdir.

Agar faqat car va suv kerak bo‘lsa, truckni olib tashlash mumkin, lekin vergulni saqlash kerak:

const vehicles = ['mustang', 'f-150', 'expedition'];
 
const [car, , suv] = vehicles;

Destruktivlashtirish funktsiya massiv qaytaradigan holatlarda foydalidir:

Misol

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

Obyektlarni Destruktivlashtirish Funktsiya ichida obyektni ishlatishning eski usuli:

Misol Oldingi usul:

const vehicleOne = {
  brand: 'Ford',
  model: 'Mustang',
  type: 'car',
  year: 2021,
  color: 'red',
};
 
myVehicle(vehicleOne);
 
// eski usul
function myVehicle(vehicle) {
  const message = 'My ' + vehicle.type + ' is a ' + vehicle.color + ' ' + vehicle.brand + ' ' + vehicle.model + '.';
}

Yangi usul, destruktivlashtirish bilan:

Misol Destruktivlashtirish bilan:

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 + '.';
}

E'tibor bering, obyekt xususiyatlarini e'lon qilishda maxsus tartibga rioya qilish shart emas.

Biz, shuningdek, chuqur ichki obyektlarni destruktivlashtirishimiz mumkin. Buning uchun ichki obyektni ko‘rsatib, so‘ng kolon va qavslardan foydalanib, kerakli elementlarni ajratamiz:

Misol

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 + '.';
}

Ushbu sahifada

Xato haqida xabar berish