تج

تجزیه‌ی شیء در JavaScript

1 تمرین

درباره‌ی تجزیه‌ی شیء

«تجزیهٔ ساختار» شیء روشی مختصر برای استخراج ویژگی‌ها از یک شیء است. نحوهٔ نگارش آن شبیه یک عبارت شیء تحت‌اللفظی است، اما به‌جای سمت راست، در سمت چپ انتساب قرار می‌گیرد.

const weather = {
  sun: '☀️',
  sun_behind_small_cloud: '🌤️',
  sun_behind_cloud: '⛅',
  sun_behind_large_cloud: '🌥️',
  sun_behind_rain_cloud: '🌦️',
  cloud: '☁️',
  cloud_with_rain: '🌧️',
  cloud_with_snow: '🌨️',
  cloud_with_lightning: '🌩️',
  cloud_with_lightning_and_rain: '⛈️',
};

const { sun, cloud, cloud_with_lightning } = weather;

sun;
// => '☀️'

cloud;
// => '☁️'

cloud_with_lightning;
// => '🌩️'

تغییر نام در انتساب

این نحوهٔ نگارش می‌تواند ویژگی‌ها را با کلیدشان، مثل sun، cloud و cloud_with_lightning استخراج کند، و همچنین می‌تواند نام دیگری برای متغیر انتخاب کند:

const { sun: sunny, cloud: cloudy, cloud_with_rain: rainy } = weather;

typeof cloud_with_rain;
// => 'undefined'

typeof rainy;
// => 'string'

rainy;
// => 🌧️

همچنین لازم نیست در انتساب از همهٔ مقادیر استفاده شود.

مقادیر پیش‌فرض

انتساب تجزیهٔ ساختار شیء می‌تواند مقادیر پیش‌فرض را فراهم کند، برای وقتی که مقداری در شیء مبدأ وجود ندارد:

const { sun = '🌞', tornado = '🌪️', cloud_with_snow: snowy = '❄️' } = weather;

sun;
// => '☀️'

tornado;
// => '🌪️'

snowy;
// => '🌨️'

موارد زیر مشاهده می‌شود:

  • sun از شیء weather استخراج شده است، بدون اینکه مقدارش جایگزین شود، چون در شیء weather وجود دارد.
  • tornado در شیء weather وجود ندارد، پس مقدار پیش‌فرض استفاده شده است.
  • cloud_with_snow با نام متغیر snowy استخراج شده است، بدون اینکه مقدارش جایگزین شود، چون cloud_with_snow در شیء weather وجود دارد.

تجزیهٔ ساختار پارامترهای تابع

شیء weather ویژگی‌های زیادی دارد. وقتی این شیء به یک تابع پاس داده می‌شود، می‌توان یک یا چند ویژگی را مستقیماً از آن استخراج کرد:

function weatherReport({ sun }) {
  console.log(sun);
}

weatherReport(sun);
// => '☀️'

تجزیهٔ ساختار در پیمایش for of

وقتی روی یک array (یا هر تکرارپذیر دیگری) پیمایش می‌کنید و عنصرها شیء هستند، می‌توان داخل دستور for (...) of iterable تجزیهٔ ساختار انجام داد:

const { sun: sunny, cloud: cloudy, cloud_with_rain: rainy } = weather;

const prediction = [
  {
    chance: 0.8,
    weather: sunny,
    description: 'There is a 80% chance it will remain sunny.',
  },
  {
    chance: 0.15,
    weather: cloudy,
    description:
      'There is a 15% chance the clouds will keep the sun from poking through.',
  },
  {
    chance: 0.05,
    weather: rainy,
    description: 'There is a small chance of rain.',
  },
];

for (const { weather: symbol, description } of prediction) {
  console.log(`${symbol}: ${description}`);
}

//  '☀️: There is a 80% chance it will remain sunny.'
// '☁️: There is a 15% chance the clouds will keep the sun from poking through.'
// '🌧️: There is a small chance of rain.'

مفاهیم مرتبط

array-destructuring rest-and-spread

ویرایش از طریق GitHub این پیوند در پنجره یا زبانه‌ی جدیدی باز می‌شود

تجزیه‌ی شیء را یاد بگیرید