物件

物件解構 在 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 編輯 連結會在新視窗或分頁中開啟

學習 物件解構