返回

精准之术:ES6 解构赋值实用技巧大全

前端

1.对象解构:

1.1.基本用法:

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const { name, age } = person;

console.log(name); // John
console.log(age); // 30

1.2.自定义变量名:

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const { name: firstName, age } = person;

console.log(firstName); // John
console.log(age); // 30

1.3.解构嵌套对象:

const company = {
  name: 'Acme Corporation',
  address: {
    street: '123 Main Street',
    city: 'New York',
    state: 'NY',
    zip: '10001'
  }
};

const { name, address: { city } } = company;

console.log(name); // Acme Corporation
console.log(city); // New York

2.数组解构:

2.1.基本用法:

const numbers = [1, 2, 3, 4, 5];

const [first, second] = numbers;

console.log(first); // 1
console.log(second); // 2

2.2.剩余元素:

const numbers = [1, 2, 3, 4, 5];

const [first, ...rest] = numbers;

console.log(first); // 1
console.log(rest); // [2, 3, 4, 5]

2.3.解构函数参数:

function sum(a, b) {
  return a + b;
}

const numbers = [1, 2];

const result = sum(...numbers);

console.log(result); // 3

3.高级应用:

3.1.对象默认值:

const person = {
  name: 'John'
};

const { name = 'Unknown', age = 20 } = person;

console.log(name); // John
console.log(age); // 20

3.2.解构赋值交换变量:

let a = 1;
let b = 2;

[a, b] = [b, a];

console.log(a); // 2
console.log(b); // 1

3.3.从数组中移除元素:

const numbers = [1, 2, 3, 4, 5];

const [first, ...rest] = numbers;

console.log(first); // 1
console.log(rest); // [2, 3, 4, 5]

// 从数组中移除第三个元素
const [first, second, , fourth, ...rest] = numbers;

console.log(first); // 1
console.log(second); // 2
console.log(fourth); // 4
console.log(rest); // [5]

结语:

JavaScript ES6 解构赋值作为一种强大的语法特性,极大地简化了对象和数组的处理,提升了代码的可读性和可维护性。通过学习和掌握解构赋值的实用技巧,您将成为一名更优秀的 JavaScript 开发人员。