ES6 解构基础用法和应用!
注意:解构只与语法有关,不与 let,var,const相关
一、数组解构取值
//数组---取值 let arr = ["张三", "李四","王五"]; let a = arr[0]; let b = arr[1]; let c = arr[2]; -------------------------- //值和变量数量是一一对应的时候 let arr = ["张三", "李四","王五"]; let [a,b,c] = arr; console.log(a); //张三 console.log(b); //李四 console.log(c); //王五 //值和变量数量不是一一对应的时候 let [a1,b1,c1,d1,e1]=[4,5,6] console.log(a1); //4 console.log(b1); //5 console.log(c1); //6 console.log(d1); //undefined 值和变量数量不是一一对应,多的打印Undefined
二、对象的解构取值
//定义一个对象 let obj={ username:'张三', age:18, sex:'女', hobby:['看书','游戏','唱歌'] } let {username,age,sex,hobby}=obj console.log(username,age,sex,hobby); //张三 18 女 ['看书', '游戏', '唱歌'] //深度解构 let { username,sex, age, hobby:[a2,b2,c2] } = obj; console.log(username,age,sex,a2,b2,c2); //张三 18 女 看书 游戏 唱歌 //解构 const { age, username } = { username: 'Alex', age: 18 }; //18 "Alex" //完整形式为: const { age: age, username: username } = { username: 'Alex', age: 18 }; // 18 "Alex" console.log(age, username);
三、同名、异名、深度解构
//定义一个对象 var obj2 = { userName: "张三", teacherInfo: { teacherName: "李四" }, stuList: [{ stuName: "小夫", age: 20 }, { stuName: "大熊", age: 20 } ] }
3.1 同名解构
// 同名解构 let { userName, teacherInfo, stuList } = obj2 console.log(userName,teacherInfo,stuList) //张三 {teacherName: '李四'} (2) [{…}, {…}]
3.2 异名解构
// 异名解构 let { userName: a3, teacherInfo: b3, stuList: c3 } = obj2 console.log(a3,b3,c3); //张三 {teacherName: '李四'} (2) [{…}, {…}]
3.3 深度解构
// 深度解构 let { userName, teacherInfo: { teacherName }, stuList: [{ }, { stuName } ] } = obj2 console.log(userName,teacherName,stuName); //张三 李四 大熊
四、交换变量
//交换变量 let x = 10, y = 20; console.log(x, y); //10 20 [x, y] = [y, x]; //直接将两个变量互换console.log(x,y); console.log(x,y); //20 10
五、解构的赋值
//解构的赋值 let userName3 = "张三"; let age3 = 18; let obj3 = { userName3, age3 }; console.log(obj3); //{userName3: '张三', age3: 18}
标签:username,ES6,console,log,age,用法,let,解构 From: https://www.cnblogs.com/mayue001/p/17226184.html