一、数组的结构赋值
1
2
3
4
5
6
7
let [a, b, c] = [1, 2, 3]
console.log(a, b, c)//结果:1, 2, 3
let [a, b, c] = [ , 2, ]
console.log(a, b, c)//结果:undefinded, 2 , undefinded
//指定默认值,当后面的赋值为空时取默认值
let [a = 111, b, c] = [ , 2, ]
console.log(a, b, c)//结果:111, 2 , undefinded
二、对象的结构赋值
1
2
3
4
5
let {foo, bar} = {foo:'hello', bar:'hi'}
console.log(foo, bar)//结果:hello hi
//指定默认值,当后面的赋值为空时取默认值
let {foo = '你好', bar} = {bar:'hi'}
console.log(foo, bar)//结果:你好 hi
对象属性别名(如果有了别名,那么原来的名字就无效了)
1
2
3
//eg:改变属性foo的名字为abc
let {foo: abc, bar} = {foo:'hello', bar:'hi'}
console.log(abc, bar)//结果:hello hi,此时如果输出foo的结会报错:未定义
三、字符串的解构赋值
1
2
let [a, b, c, d, e] = "hello"
console.log(a, b, c, d, e)//结果:h e l l o