越来越多的代码开始使用ES2015中引入的解构赋值,但我经常发现很难理解作者在做什么。我可以看出解构在某些情况下非常有用,但我觉得它经常会引入不必要的代码复杂性。
例如,MDN上的嵌套对象和数组解构示例使用以下代码对嵌套数组进行解构:
例如,MDN上的嵌套对象和数组解构示例使用以下代码对嵌套数组进行解构:
var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
相对于这样看起来更易读的东西,它有什么优势呢:
var englishTitle = metadata.title,
localeTitle = metadata.translations[0].title;
解构赋值可以解决哪些问题?
什么情况下应该使用它们,什么情况不应该使用?
localeTitle
是translations
数组中第一个对象的标题属性。 - MinusFourconst { foo, bar } = this.props;
相对于const foo = this.props.foo; const bar = this.props.bar;
。 - zerkms