对象

对象解构 属于 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 编辑 该链接会在新窗口或标签页中打开

学习 对象解构