5-3 解构赋值详解

45 阅读2分钟

按照一定模式,从数组和对象中取值,对变量进行赋值

解构赋值其实就是一种模式的匹配,只要等号两边的模式是完全相同的,那么左边的变量就能赋值成右边的值

数组的解构赋值

// 常规写法

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

// 解构赋值其实就是一种模式的匹配,只要等号两边的模式是完全相同的,那么左边的变量就能赋值成右边的值

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, 4]

对象的解构赋值

let user = {
  name: 'uu',
  age: 4
}

let {name, age} = user
console.log(name, age)
  • 在对象里面key 是唯一的,在对象解构的时候,是通过key的名称去对应的,而不是通过顺序去对应的

  • 也可以使用 :去重新定义别名

let {age: uage, name: uname} = user
console.log(uname, uage)

字符串的解构赋值

let str = 'xiao'
for(let i = 0; i < str.length; i++){
  console.log(str[i])
}
可以把字符串的解构当作数组的解构
let [a, b, c, d] = str
console.log(a, b, c, d) // x i a o

应用场景

应用场景中的默认值,如果没传值直接使用默认值,传值的情况下使用传入的值

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

// --------------------------
let {name, age = 18} = {
  name: 'uu',
  // age: 4
}
console.log(name, age)  // uu 18

// --------------------------
function foo(){
  console.log(123)
}
let [a = foo()] = [] // 123
let [a = foo()] = [1]

// --------------------------
function foo([a, b, c]){
  console.log(a, b, c)
}
let arr = [1, 2, 3]
foo(arr)


// --------------------------
function foo(name, age, school = 'juejin'){
  console.log(name, age, school)
}
let obj = {
  name: 'uu',
  age: 4,
  school: 'xxx'
}
foo(obj)
// --------------------------

function foo(){
  let obj = {
    name: 'uu',
    age: 4,
    school: 'xxx'
  }
}
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)