How to destructure an array in ES6?

In ES6, you can use destructuring assignment syntax to extract values from arrays or objects and assign them to variables. Here is how to use destructuring assignment syntax for arrays and objects:

  1. Array destructuring assignment:
// 简单数组解构赋值
const [a, b, c] = [1, 2, 3];
console.log(a); // 输出: 1
console.log(b); // 输出: 2
console.log(c); // 输出: 3

// 忽略某些元素
const [d, , e] = [4, 5, 6];
console.log(d); // 输出: 4
console.log(e); // 输出: 6

// 剩余元素赋值给一个新数组
const [f, ...rest] = [7, 8, 9];
console.log(f); // 输出: 7
console.log(rest); // 输出: [8, 9]
  1. Destructuring assignment for objects:
// 简单对象解构赋值
const {x, y} = {x: 1, y: 2};
console.log(x); // 输出: 1
console.log(y); // 输出: 2

// 重命名变量
const {a: m, b: n} = {a: 3, b: 4};
console.log(m); // 输出: 3
console.log(n); // 输出: 4

// 默认值
const {p = 5, q = 6} = {p: 7};
console.log(p); // 输出: 7
console.log(q); // 输出: 6

It’s important to note that destructuring syntax is just a convenient way to extract values from arrays or objects, so make sure that the variable names match the property names in the array or object when using it.

bannerAds