Skip to content

解构与展开

解构

  1. 基本语法
ts
const [a, b, c] = [1, 2, 3]
console.log(a, b, c) // 1 2 3
  1. 忽略某些元素
ts
const [first, , third] = [10, 20, 30]
console.log(first, third) // 10 30
  1. 设置默认值

只有当对应位置是 undefined 时,默认值才会生效。

ts
const [a = 1, b = 2, c = 3] = [10, 20]
console.log(a, b, c) // 10 20 3
  1. 函数返回值
ts
function getValues() {
  return [100, 200, 300]
}

const [x, y, z] = getValues()
console.log(x, y, z) // 100 200 300
  1. 数组解构赋值
ts
const [name, ...args] = ['Alice', 18, 'Developer', 'Shanghai']

console.log(name) // 'Alice'
console.log(args) // [18, 'Developer', 'Shanghai']

展开