es6解构赋值常用方法
解构赋值
数组解构
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 {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'
利用结构赋值实现参数定义
一般我们在定义函数的时候,如果函数有多个参数时,在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})