The basic usage of array destructuring
The Concept of Array Destructuring
Array destructuring is a syntax feature introduced in ES6 that allows extracting values from arrays or iterable objects according to a specific pattern and assigning them to variables. This approach is essentially pattern matching—as long as the patterns on both sides of the equals sign match, the variables on the left will be assigned the corresponding values.
// Basic example
const arr = [1, 2, 3];
const [a, b, c] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
Basic Destructuring Patterns
The simplest form of destructuring involves assigning array elements to variables in order. During destructuring, the variable names on the left are placed in square brackets and correspond one-to-one with the positions in the right-hand array.
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;
console.log(firstColor); // "red"
console.log(secondColor); // "green"
Unwanted elements can be skipped by using commas as placeholders:
const numbers = [1, 2, 3, 4];
const [,, thirdNumber] = numbers;
console.log(thirdNumber); // 3
Default Values
When the destructured value is strictly equal to undefined
, default values can be used:
const [a = 5, b = 7] = [1];
console.log(a); // 1
console.log(b); // 7
const [x = 1, y = 2] = [undefined, null];
console.log(x); // 1
console.log(y); // null
Nested Array Destructuring
Destructuring also works with nested arrays:
const nested = [1, [2, 3], 4];
const [i, [j, k], l] = nested;
console.log(i); // 1
console.log(j); // 2
console.log(k); // 3
console.log(l); // 4
Rest Pattern
The rest pattern can be used to assign the remaining elements of an array to a variable:
const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2, 3, 4]
Note that the rest element must be the last element in the destructuring pattern:
// This will throw an error
const [...rest, last] = [1, 2, 3, 4];
Variable Swapping
Array destructuring makes it easy to swap variable values without a temporary variable:
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
Function Parameter Destructuring
Function parameters can also use array destructuring:
function sum([x, y]) {
return x + y;
}
console.log(sum([1, 2])); // 3
Destructuring Iterable Objects
Array destructuring is not limited to arrays—it works with any iterable object:
const [a, b, c] = 'xyz';
console.log(a); // 'x'
console.log(b); // 'y'
console.log(c); // 'z'
const [first, ...rest] = new Set([1, 2, 3]);
console.log(first); // 1
console.log(rest); // [2, 3]
Destructuring Failure Cases
When destructuring fails, the variable's value will be undefined
:
const [missing] = [];
console.log(missing); // undefined
Practical Use Cases
Array destructuring is useful in many scenarios:
- Functions returning multiple values:
function getCoordinates() {
return [12.345, 67.890];
}
const [latitude, longitude] = getCoordinates();
- Regular expression matching results:
const url = 'https://example.com/users/123';
const matches = url.match(/\/users\/(\d+)/);
const [, userId] = matches;
console.log(userId); // "123"
- Processing CSV data:
const csvLine = '1997,Ford,E350';
const [year, make, model] = csvLine.split(',');
Notes
When using array destructuring, keep the following in mind:
- The right-hand side of destructuring assignment must be an iterable object.
- If the destructuring target is not iterable, a
TypeError
will be thrown. - The rest element must be the last element.
- Default values only take effect when the value is
undefined
. - Destructuring does not affect the original array.
// Error example
const [a, b] = {}; // TypeError: {} is not iterable
Differences from Object Destructuring
Although array destructuring and object destructuring are both forms of destructuring assignment, they have key differences:
- Array destructuring uses square brackets
[]
, while object destructuring uses curly braces{}
. - Array destructuring matches by position, while object destructuring matches by property name.
- Array destructuring can skip elements, while object destructuring cannot skip properties.
// Array destructuring
const [x, , y] = [1, 2, 3];
// Object destructuring
const {a, c} = {a: 1, b: 2, c: 3};
Advanced Usage Examples
Combined with other ES6 features, array destructuring enables more complex operations:
- Combined with the spread operator:
const [first, ...others] = ['a', 'b', 'c', 'd'];
console.log(others.join('-')); // "b-c-d"
- Usage in loops:
const users = [
['John', 30],
['Jane', 25]
];
for (const [name, age] of users) {
console.log(`${name} is ${age} years old`);
}
- Multi-level nested destructuring:
const metadata = [
{ title: 'Scratchpad', tags: ['javascript', 'css'] },
{ title: 'Work', tags: ['react', 'redux'] }
];
const [, { tags: [, framework] }] = metadata;
console.log(framework); // "redux"
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:与普通字符串拼接的性能对比
下一篇:对象解构的基本用法