ES系列 | 解构赋值

320 阅读2分钟

「这是我参与2022首次更文挑战的第4天,活动详情查看:2022首次更文挑战」。

ES系列文章

解构赋值

是一种针对数组和对象模式的匹配,对其变量进行赋值

数组解构

  • 传统模式下数组解构(步骤繁琐)
let arr= [1, 2, 3];
let a = arr[0]
let b = arr[1]
let c = arr[2]
console.log(a, b, c)
//1 2 3
  • es6数组解构
基本
let [a, b, c]= [1, 2, 3];
console.log(a, b, c)
//1 2 3
嵌套
let [a, b, [c, d]]= [1, 2, [3, 4]];
console.log(a, b, c,d)
//1 2 3 4

let [a, b, [c,]]= [1, 2, [3, 4]];
console.log(a, b, c)
//1 2 3 

let [a, b, c]= [1, 2, [3, 4]];
console.log(a, b, c)
//1 2 [3 4]
不完全解构
let [a, b, c, d]= [1, 2, [3, 4]];
console.log(a, b, c,d)
//1 2 [3 4] undefined
解构默认值
let [a, b, c, d = 5]= [1, 2, [3, 4], 6];
console.log(a, b, c,d)
//1 2 [3 4] 6
//以传值为准否则取默认值

对象解构

  • 传统模式对象解构(步骤繁琐)
let user = {
    name: 'xxx'
    age: 34
}
let name = user.name
let age = user.age
console.log(name, age)
// xxx 34
  • es6对象解构
基本
let user = {
    name: 'xxx'
    age: 34
}
let {name, age} = user
console.log(name, age)
// xxx 34
let user = {
    name: 'xxx'
    age: 34
}
let {name: uname, age: uage} = user
console.log(uname, uage)
// xxx 34

字符串解构

let list= 'abcde';
for (let i = 0; i < list.lenght; i++){
    console.log(list[i])
}
  • 字符串数组解构
let list= 'abcde';
let [a, b, c, d, e] = list
console.log(a, b, c, d, e)

应用

  • 数组默认值
let [a, b, c = 8] = [4, 5]
console.log(a, b, c)
// 4 5 8

let [a, b, c = 8] = [4, 5, 6]
console.log(a, b, c)
// 4 5 6
  • 对象默认值
let {name, age } = {
    name: 'xxx'
    age: 34
}
console.log(name, age)
// xxx 34

let {name, age = 18} = {
    name: 'xxx'
    //age: 34
}
console.log(name, age)
// xxx 18
function foo(){
    console.log(123)
}
let [a = foo()] = [1]  //let [a = foo()] = []
若未赋值取方法初始值
  • 函数参数解构赋值
function foo([a, b, c]){
    console.log(a, b, c)
}
let arr = [1, 2, 3]
foo(arr)
// 1 2 3
  • 函数对象解构赋值
function foo({name, age, school = 'abcde' }){
    console.log(name, age, school)
}
let ogj = {
    name: 'xxx'
    age: 34
}
foo(obj)
// xxx 34 abcde
function foo() {
    let ogj = {
        name: 'xxx'
        age: 34
    }
    return ogj
}
let {name, age} = foo()
console.log(name, age)

  • json
let json = '{"a": "hello", "b": "world"}'
let {a, b} = JSON.parse(json)
console.log(a, b)

一个前端小白,若文章有错误内容,欢迎大佬指点讨论!