对象解构:

对象的属性没有次序,变量必须与属性同名,才能取到正确的值。

let {a, b} = {a: 'aaaa', b: 'bbbb'} // a='aaaa' b='bbbb'

let obj = {d: 'aaaa', e: {f: 'bbbb'}}
let {d, e:{f}} = obj // 嵌套解构 d='aaaa' f='bbbb'

let g;
(g = {g: 'aaaa'}) // 以声明变量解构 g='aaaa'

let [h, i, j, k] = 'nice' // 字符串解构 h='n' i='i' j='c' k='e'

如果变量名与属性名不一致,那必须写成这样

var {foo:baz} = {foo:'aaa'}   // baz ='aaa'

对象的解构赋值也可以指定默认值,默认值的生效条件是,对象的属性值严格等于undefined

var {x=3} = {x:undefined}
x  //3

var {x=3} = {x:null}
x  //null

数组解构:

这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。

let [a, b, c] = [1, 2, 3] // a=1, b=2, c=3
let [d, [e], f] = [1, [2], 3] // 嵌套数组解构 d=1, e=2, f=3
let [g, ...h] = [1, 2, 3] // 数组拆分 g=1, h=[2, 3]
let [i,,j] = [1, 2, 3] // 不连续解构 i=1, j=3
let [k,l] = [1, 2, 3] // 不完全解构 k=1, l=2
let [x,y,z] = ['a']  // 不成功解构 x='a', y= undefined,z=undefined

给变量赋值:

es5对变量赋值

var data = {userName: 'aaaa', password: 123456}
var userName = data.userName
var password = data.password
console.log(userName)
console.log(password)
var data1 = ['aaaa', 123456]
var userName1 = data1[0]
var password1 = data1[1]
console.log(userName1)
console.log(password1)

解构赋值

const {userName, password} = {userName: 'aaaa', password: 123456}
console.log(userName)
console.log(password)
const [userName1, password1] = ['aaaa', 123456]
console.log(userName1)
console.log(password1)

函数参数的定义:

一般我们在定义函数的时候,如果函数有多个参数时,在es5语法中函数调用时参数必须一一对应,否则就会出现赋值错误的情况

function personInfo(name, age, address, gender) {
      console.log(name, age, address, gender)
}
personInfo('william', 18, 'changsha', 'man')

上面这个例子在对用户信息的时候需要传递四个参数,且需要一一对应,这样就会极易出现参数顺序传错的情况,从而导致bug,接下来来看es6解构赋值是怎么解决这个问题的:

function personInfo({name, age, address, gender}) {
  console.log(name, age, address, gender)
}
personInfo({gender: 'man', address: 'changsha', name: 'william', age: 18})
02-10 15:55