ES6-解构赋值

239 阅读1分钟

数据结构取值

let arr = ['a','b'];
let [first,second] = arr
console.log(first)
// a

复杂数据结构取值

//跳过
let arr = ['a','b','c','d']
let [first,,third] = arr
console.log(first,third)
//a c
let arr = 'abcd'
let [first,,third] = arr
console.log(first,third)
//a c
//[]后面解构的是一个可遍历的对象 new Set() new Map()等

对象属性重新赋值

let user = {name:'kimi',age:18}
{user.name,user.age} = ['jojo',6]
console.log(user)
//{name:'jojo',age:6}

循环体中的解构赋值

let user = {name:'kimi',age:18}
for (let [k,v] of Object.entries(user)){
    console.log(k,v)
}

变量

let arr = [1,2,3,4,5,6,7,8,9]
let [first,second,...last] = arr
console.log(first,second,last)
1,2,[3,4,5,6,7,8,9]

类型转换

//set转换
let set = new Set([1,2,3]);
let arr = [...set]
//map转换
let set = new Map([1,2,3]);
let arr = [...set]
//参数转换
[...args]

对象的解构赋值

let opts = {
    name:'kimi',
    age:18,
    add:'hangzhou'
}
let {name:name1,age} = opts
console.log(name1,age)
//:重新定义属性名 避免冲突
//kimi 18

let {name,...last} = opts
console.log(name,last)
// kimi {age:18,add:'hangzhou'}

//添加或改变值
let {name,sex='boy',age,add} = opts
console.log(name,sex,age,add)
//kimi boy 18 hangzhou

//复杂数据解构
let opts = {
    goods:{
        bad:{
            price:200
        }
    },
    id:12,
    items:['cake','apple']
}
let {goods:{bad:{price}},id,items:[item1]} = opts
console.log(price,id,item1)
//200 12 cake