杂货小铺之ES6+ 🍳 解构赋值
2020-07-07 本文已影响0人
羊驼驼驼驼
es.png
-
解构赋值
📖 在 ES6 中新增了变量赋值的方式:解构赋值。允许按照一定模式,从数组和对象中提取值,对变量进行赋值
- 单独赋值给变量;
let [a, b, c] = [1,2,3]
console.log(a, b, c) // 1 2 3
🔎 :
解构赋值重点在于赋值
,赋值的元素是要拷贝出来赋值给变量,赋值的元素本身是不会改变的
-
数组的解构赋值;
- 赋值元素可以是任意可遍历的对象;
let [a, b, c] = 'abc'; // ["a","b","c"] let [one, two, three] = new Set([1,2,3]);
- 被赋值的变量还可以是对象的属性,不局限于单纯的变量;
let user = {}; [user.first, user.second] = 'hello world'.split(' '); console.log(user.first, user.second); // hello world
- 循环体中的应用;
// 配合Object.entries使用 let user = { name: "Xiao", age: 12 }; for (let [key, value] of Object.entries(user)) { console.log(`${key}:${value}`); // name:Xiao age:12 }
// map let user = new Map(); user.set("name", "Xiao"); user.set("age", 12); for (let [key, value] of user.entries()) { console.log(`${key}:${value}`); // name:Xiao age:12 }
- 跳过赋值元素;
let [a, , ,e] = [1,2,3,4]; console.log(e); // 4
- rest参数;
let [name1, name2, ...rest] = ["hello", "world", "hi", "newWorld"]; console.log(name1); // hello console.log(name2); // world console.log(rest[0]); // hi console.log(rest[1]); // newWorld console.log(rest.length); // 2
🔎 :
可以使用rest来接受赋值数组的剩余元素,不过要确保这个rest参数是放在被赋值变量的最后一个位置上。- 默认值;
let [first, second] = []; console.log(first); // undefined console.log(second) // undefined // 也可以给变量赋予默认值,防止undefined的出现 let [first = "hello", second = "world"] = ["hi"]; console.log(first); // hi console.log(second); // world
-
对象的解构赋值;
- 基本用法;
// 在赋值的左侧声明一个和Object结构等同的模板,然后把关心属性的value指定为新的变量 let options = { name: "Title", width: 100, height: 200, }; let { name, width, height } = options; console.log(name); // Title console.log(width); // 100 console.log(height); // 200 // 也可以用其他的自定义变量名 let {width: w, height: h, name} = options; console.log(w); // 100 console.log(h); // 200 console.log(name) // Title
🔎 :
在这个解构赋值的过程中,左侧的"模板"结构要和右侧的Object一致,但是属性的顺序无需一致。- 默认值;
let options = { name: "Title", }; let { width = 200, height = 100, name } = options; console.log(width); // 200 console.log(height); // 100 console.log(name); // Title
- rest运算符;
let options = { name: "Title", width: 100, height: 200, }; let { name, ...rest } = options; console.log(rest.width); // 100 console.log(rest.height); // 200
- 嵌套对象;
// 被赋值的结构和右侧赋值的元素一致 let options = { size: { width: 100, height: 200, }, items: ["Header", "Menu"], extra: true, }; let { size: { width, height }, items: [item1, item2], name = "Title", } = options; console.log(name); // Title console.log(width); // 100 console.log(height); // 200 console.log(item1); // Header console.log(item2); // Menu
-
字符串的解构赋值;
// 可以当做是数组的解构 let str = "hello"; let [a, b, c, d, e] = str; console.log(a, b, c, d, e); // h e l l o
🌻🌻🌻🌻🌻🌻🌻🌻🌻🌻🌻🌻🌻🌻
以上是对解构赋值的小小的总结~
推荐给大家几篇干货:
https://ponyfoo.com/articles/es6-destructuring-in-depth
https://www.sitepoint.com/javascript-ui-frameworks/