乐趣区

关于javascript:ES6十-Destructure解构

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] = arr
console.log(firstName, surName)
//hello world

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

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

//String
let str = 'abcd'
let [,, thirdName] = str
console.log(thirdName) // c

//Set
let [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] = arr
console.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] = arr
console.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} = options
console.log(title, width, height)
// menu 100 200

能够换变量名

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

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

默认值

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

rest 运算符

let options = {
    title: 'menu',
    width: 100,
    height: 200
}

let {title, ...last} = options
console.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] } = options
console.log(width2, height, item1)
//100 200 "Cake"

学习幅员

退出移动版