Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
- Deconstruction:
That is to extract a variable from an object or array and assign it to it
- Why:
Extracting data objects requires assignment by assignment, which may mine the entire structure for a small piece of data. ES6 adds deconstruction to arrays and objects to facilitate extracting data
3.# Object and function argument deconstruction
An array of deconstruction
- low
let a = 1
let b = 2
Copy the code
- general
let a = 1, b = 2
Copy the code
- good
let [a, b] = [1, 2]
Copy the code
Similar to numeric swapping, it can be implemented in one line of code
let [a, b] = [1, 2]
[a, b] = [b, a]
console.log(a, b) // 2, 1
Copy the code
If (let [a] = 1, let [a] = 1) TypeError: This is a normal case, and sometimes some special cases are encountered
let [ , , a] = [0, 1, 2]
console.log(a) // 2
Copy the code
A corresponds to the 2 on the right, so it’s also going to be 2
let [a, ,b] = [1, 2, 3]
console.log(a) // 1
console.log(b) // 3
Copy the code
The middle is undefined, of course, so a is at 1 and B is at 3
let [a, b, c] = [1]
console.log(a) // 1
console.log(b) // undefined
console.log(c) // undefined
Copy the code
If there is no value, the value will be undefined by default, so a will be 1, b and C will be undefined
let [a, b, ...c] = [1, null]
console.log(a) // 1
console.log(b) // null
console.log(c) // []
Copy the code
C is an array, if empty, an empty array, b is a non-array, if empty, undefined, and if null, null
let [a, ...b] = [1, 2, 3, 4]
console.log(a) // 1
console.log(b) // [2, 3, 4]
Copy the code
An array can eat all the values behind it but it can’t be defined at the end of the array, so you get an error, for example
let [...a, b] = [1, 2, 3, 4]
// error: Rest element must be last element
Copy the code
let [a = 1, b] = []
console.log(a) // 1
console.log(b) // undefined
Copy the code
When there is a default value in the structure, the default value takes precedence, but there is one case where null is overridden
let [a = 1] = [null]
console.log(a) // null
Copy the code