ES6 Destructuring

Destructuring

1
2
3
4
5
6
7
8
9
const person = {
first: 'Wes',
last: 'Bos',
country: 'Canada',
city: 'Hamilton',
twitter: '@wesbos'
};
const first = person.first;
const last = person.last;

缺点,需重新定义两个变量,然后得重复好多代码,总之麻烦

使用 Destructuring

1
2
3
4
5
6
7
8
9
10
11
12
var person = {
name: 'xwill',
age: 24
}

var { name, age } = person;
console.log(name); //xwill
console.log(age); //24

//也可以重命名变量
var { name: myName } = person;
console.log(myName); //xwill

更复杂的结构

1
2
3
4
5
6
7
8
9
10
11
12
13
const wes = {
first: 'Wes',
last: 'Bos',
links: {
social: {
twitter: 'https://twitter.com/wesbos',
facebook: 'https://facebook.com/wesbos.developer',
},
web: {
blog: 'https://wesbos.com'
}
}
};

如果想拿出 twitter 和 facebook

1
2
3
const twitter = wes.links.social.twitter;
const facebook = wes.links.social.facebook;
// Annoying!

使用 Destructuring

1
2
const { twitter, facebook } = wes.links.social;
console.log(twitter, facebook); // logs the 2 variables

Destructuring 设置默认值

1
2
3
4
5
const obj = {
name: 'xwill',
age: 24
}
const { name, age, height = 175 } = obj;

注意,这里 height 并不能在 obj 的属性中,所以,当 Destructuring 一个不存在的属性,如果设置了默认值,则相当于定义了一个新的变量,并赋予默认值。

1
2
3
4
5
const person = {
name: 'xwill',
age: 24
}
const { name, age = 20, height: myHeight = 175 } = 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,赋值都无效。只有属性不存在的情况下,赋值才有效。