Destructuring
1 | const person = { |
缺点,需重新定义两个变量,然后得重复好多代码,总之麻烦
使用 Destructuring
1 | var person = { |
更复杂的结构
1 | const wes = { |
如果想拿出 twitter 和 facebook
1 | const twitter = wes.links.social.twitter; |
使用 Destructuring
1 | const { twitter, facebook } = wes.links.social; |
Destructuring 设置默认值
1 | const obj = { |
注意,这里 height 并不能在 obj 的属性中,所以,当 Destructuring 一个不存在的属性,如果设置了默认值,则相当于定义了一个新的变量,并赋予默认值。
1 | const person = { |
分析:
- First we create a new const var called myHeight.
- Next we look for person.height. If there was a person.height property, it would be put into the myHeight varaible.
- There isn’t a height property on our person object, so we fall back to the default of 175.
注意,这里 age 的默认赋值无效。只要 obj 有某属性属性,destructuring 时无论是 undefined,null,0,false,赋值都无效。只有属性不存在的情况下,赋值才有效。