Destructure

  • Array-Destructure

    • 根本用法
    • 跳过赋值变量、能够是任意可遍历的对象
    • 右边能够是对象属性
    • rest变量
    • 默认值 & 当解构赋值值不够的状况
  • Object-Destructure

    • 根本用法
    • 能够换变量名
    • 默认值
    • rest运算符
    • 嵌套对象
  • ES6-ES10学习幅员

解构赋值:
应用数组索引去应用变量,不如间接赋值一个变量,然而也不适宜用let申明很多变量

Array-Destructure

根本用法

let arr = ['hello', 'world']// 通过索引拜访值let firstName = arr[0]let surName = arr[1]console.log(firstName, surName)// hello world

ES6

let arr = ['hello', 'world']let [firstName, surName] = arrconsole.log(firstName, surName)//hello world

跳过赋值变量、能够是任意可遍历的对象

//跳过某个值//Arraylet arr = ['a', 'b', 'c', 'd']let [firstName,, thirdName] = arr // 右边是变量,左边是一个可遍历的对象,包含Set和Mapconsole.log(firstName, thirdName) // a c//Stringlet str = 'abcd'let [,, thirdName] = strconsole.log(thirdName) // c//Setlet [firstName,, thirdName] = new Set([a, b, c, d])console.log(firstName, thirdName) // a c

右边能够是对象属性

给对象属性重新命名

let user = { name: 's', surname: 't' };[user.name,user.surname] = [1,2]//花括号和中括号之间必须要有分号console.log(user)// { name: 1,surname: 2}

rest变量

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]let [firstName,, thirdName,...last] = arrconsole.log(firstName, thirdName, last)// 1 2 [3, 4, 5, 6, 7, 8, 9]// 下面如果只赋值firstName和thirdName,那么剩下的参数arr会被回收掉,如果不想3-9的元素被删掉,那么能够用[...rest]// rest只能在最初一个元素中应用

默认值 & 当解构赋值值不够的状况

从前往后没有取到为undefined

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]let [firstName,, thirdName,...last] = arrconsole.log(firstName, thirdName, last)// 1 2 [3, 4, 5, 6, 7, 8, 9]let arr = [1, 2, 3]let [firstName,, thirdName,...last] = arr// 1 2 [3]let arr = [1, 2]let [firstName,, thirdName,...last] = arr// 1 2 []let arr = [1]let [firstName,, thirdName,...last] = arr// 1 undefined []let arr = []let [firstName,, thirdName,...last] = arr// undefined undefined []//默认没有参数,会为undefined,如果这个时候进行数字运算的时候,就会有问题//如果防止这种状况,就要进行默认值的赋值let arr = []let [firstName = 'hello',, thirdName,...last] = arr// hello undefined []

Object-Destructure

根本用法

let options = {    title: 'menu',    width: 100,    height: 200}let { title, width, height } = optionsconsole.log(title, width, height)// menu 100 200

能够换变量名

如果有变量抵触怎么办?不能用简写模式

// 上面title是匹配属性名提取变量名称// title2是新的变量名let {title: title2, width, height} = optionsconsole.log(title2, width, height)//  menu 100 200

默认值

let options = {    title: 'menu',    height: 200}let {title: title2, width = 130, height} = optionsconsole.log(title2, width, height)//  menu 130 200

rest运算符

let options = {    title: 'menu',    width: 100,    height: 200}let { title, ...last } = optionsconsole.log(title, last)//menu {width: 100, height: 200}

嵌套对象

let options = {    size: {        width: 100,        height: 200    },    item: ['Cake', 'Donut'],    extra: true}let { size: { width: width2, height }, item: [item1] } = optionsconsole.log(width2, height, item1)//100 200 "Cake"

学习幅员