ES6系列之【解构赋值】

ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值

解构是一种打破数据结构,将其拆分为更小部分的过程

let details = {
    firstName:'Code',
    lastName:'Burst',
    age:22
}

//1、对象的解构赋值
const {firstName,age} = details;

console.log(firstName); // Code
console.log(age);       // 22

//2、自定义变量名称
const {firstName:newname,age:newage} = details;


//3、运用解构赋值可以设置形参的认值
const student = {
    name:'Lily',
    age:20,
    scores:{
        math:95,
        chinese:98,
     
    }
}
function showscore(student){
    const { name,scores:{ math = 0,chinese = 0, english = 0}} = student;
    console.log('学生名:' + name);
    console.log('数学成绩:' + math);
    console.log('语文成绩:' + chinese);
    console.log('英语成绩:' + english);
}
showscore(student) 
//学生名:Lily
//数学成绩:95
//语文成绩:98
//英语成绩:0

//数组的解构赋值

let arr=['Lily',18,'168cm']
let [name,age]=arr

console.log(name,age)

//按照顺序结构
let arr=['Lily',18,'168cm']
let [name,,high]=arr
console.log(name,high) //Lily 168cm

//同样,也可以设置认值
let arr=['Lily',18,'168cm']
let [name,age,high,weight='45kg']=arr
console.log(name,age,high,weight) //Lily 18 168cm 45kg

//配合...扩展运算符
let colors = ['red','green','blue'];
let [firstColor,...otherColors] = colors;
console.log(firstColor);  // red
console.log(otherColors); // ['green','blue']

let node = {
    name:'foo',
    loc:{
        start:{
            line:1,
            column:1
        }
    },
    range:[0,3]
}
let {
    loc:{start:{line}},
    range:[startIndex]
} = node;
console.log(line);       // 1
console.log(startIndex); // 0

总结,使用场景:

1、设置函数形参的认值

2、方便从 JSON 中提取数据,不再需要遍历整个解构了。

相关文章

原文连接:https://www.cnblogs.com/dupd/p/5951311.htmlES6...
以为Es6,javascript第一次支持了module。ES6的模块化分为导...
视频讲解关于异步处理,ES5的回调使我们陷入地狱,ES6的Prom...
TypeScript什么是TypeScript?TypeScript是由微软开发的一款开...
export class AppComponent { title = 'Tour of heroes...
用 async/await 来处理异步昨天看了一篇vue的教程,作者用as...