This is the second day of my participation in the First Challenge 2022
Hi, I’m CUGGZ. Today we’re going to look at some useful techniques for ES6 deconstruction assignment
My wechat: CUG-gz
Wechat official account: Front-end charge bank
1. Basic Concepts
Here’s an example of why deconstruction is needed:
const student = {
name: 'ZhangSan'.age: 18.scores: {
math: 19.english: 85.chinese: 100}};function displayInfo(student) {
console.log('name:', student.name);
console.log('math:', student.scores.math);
console.log('english:', student.scores.english);
console.log('chinese:', student.scores.chinese);
}
displayInfo(student);
Copy the code
This works, but the code looks redundant. Also, if the object is deeply nested internally, the access chain of the object becomes very long. While this is not a big deal, using deconstructed assignment makes the code simpler and easier to read.
Let’s look at what deconstructed assignment is. Description of deconstruction assignment in MDN:
The destruct assignment syntax is a Javascript expression. By deconstructing assignments, attribute values can be taken out of the object/array and assigned to other variables.
In effect, structure assignment is the decomposition of a complex structure into its simpler parts. Destruct assignment syntax can be used for variable declarations or variable assignments. In addition, nested structures can be handled using nested destruct assignment syntax.
For example, deconstruct the object in the above example:
function displayInfo(student) {
const { name, scores: {math, english, chinese} } = student;
console.log('name:', name);
console.log('math:', math);
console.log('english:', english);
console.log('chinese:', chinese);
}
Copy the code
Doesn’t that look a lot cleaner.
Second, deconstruct classification
According to MDN’s definition of deconstruction assignment, we can divide deconstruction assignment into two categories:
- Object to deconstruct
- An array of deconstruction
Let’s take a look at the two types of deconstructive assignment separately.
1. Object deconstruction assignment
Object deconstruction, also known as the object attribute allocation pattern, allows us to assign object attribute values to corresponding variables. It can be written in two ways:
let obj = {x: 1.y: 2.z: 3};
let {x: a, y: b, z: c} = obj;
console.log(a, b, c)
let {x, y, z} = obj;
console.log(x, y, z)
Copy the code
- The first (line 3) is the full form of object deconstruction, where each property of the object is assigned a variable, with the attributes in the source object preceded by the colon and the attributes to be assigned after the colon;
- The second (line 5) is shorthand for object deconstruction, which can be used when the attributes of the object are consistent with the attributes to be assigned.
If you need to assign a value to an existing variable, you need to pay extra attention:
let obj = {x: 1.y: 2.z: 3};
let x = 0, y = 0, z = 0;
({x, y, z} = obj)
console.log(x, y, z)
Copy the code
Note that the assignment expression is enclosed in parentheses. If omitted, the destructed object is treated as a block statement, which cannot be placed to the left of the assignment expression.
When using destruct assignment, you can pass a default value to a variable:
const person = {
name: 'ZhangSan'.height: 180
};
const { name, height, age = 25 } = person;
console.log(name, height, age);
Copy the code
Here we assign a default value to age. When there is no age attribute on the source object, age is assigned the default value 25 instead of undefined.
If the assigned object attribute is undefined, the default value is used:
const {x = 2} = {x: undefined};
console.log(x); / / 2
Copy the code
2. Array deconstruction assignment
When array destructuring is used, iterators are actually used to separate the required values from the structure source. Therefore, we can use array structures for iterable values, including strings, arrays, collections, function maps, and DOM elements. We can also use deconstruction assignment in conjunction with extension operators.
(1) String
let message = 'Hello';
let [a, b] = message;
let [x, y, ...z] = message;
console.log(a, b); // H e
console.log(x, y, z); // H e ['l', 'l', 'o']
Copy the code
(2) Array
let numbers = [1.2.3];
let [x, y, z] = numbers;
console.log(x, y, z); / / 1 2 3
Copy the code
(3) Set
let set = new Set().add('foo').add('bar');
let [a, b] = set;
console.log(a, b); // foo bar
Copy the code
(4) the Map
let map = new Map().set('a'.1).set('b'.2);
let [x, y] = map;
console.log(x, y); // ["a", 1] ["b", 2]
Copy the code
In array deconstruction, each variable in the array of variables is mapped to the corresponding item at the same index on the deconstructed array.
If an item in the deconstruction is not needed, separate it with the comma operator:
const rgb = [200.255.100];
const [,, blue] = rgb;
console.log(blue); / / 100
Copy the code
As with object destruction, you can use array destruction to set defaults for local variables:
const rgb = [200];
const [red = 255, green, blue = 255] = rgb;
console.log(`R: ${red}, G: ${green}, B: ${blue}`);
Copy the code
If the variable already exists, it can be written like this:
let red = 100, green = 200, blue = 50;
const rgb = [200.255.100];
[red, green] = rgb;
console.log(`R: ${red}, G: ${green}, B: ${blue}`);
Copy the code
Unlike object deconstruction, there is no need to enclose the array in parentheses.
If the value assigned to a variable is undefined, the default value is used:
const [x = 1] = [undefined];
console.log(x); / / 1
Copy the code
The default value here does not have to be a fixed value, it can be a calculated property:
function foo() {
return 1;
}
let obj1 = {x: 2};
let obj2 = {x: undefined};
let {x=foo()} = obj1;
console.log(x); / / 2
let {x=foo()} = obj2;
console.log(x); / / 1
Copy the code
If we want to assign some elements of the array to variables, and the rest of the array to specific variables, we can do this:
let [greeting,...intro] = ["Hello"."I" , "am"."CUGGZ"];
console.log(greeting); // "Hello"
console.log(intro); // ["I", "am", "CUGGZ"]
Copy the code
Nested deconstruction
The above knowledge of deconstruction is common arrays and objects. In fact, destruct assignment can be used for nested arrays and nested objects. For example, in the first example of this article, there is a destructed nested object:
const student = {
name: 'ZhangSan'.age: 18.scores: {
math: 19.english: 85.chinese: 100}};const { name, scores: {math, english, chinese} } = student;
Copy the code
Let’s look at another example of a nested array deconstruction:
let numbers = [1[2.3.4].5];
let [a, [b, c, d], e] = numbers;
console.log(a, b, c, d, e); // 1, 2, 3, 4, 5
Copy the code
Five, the use of skills
1. Function deconstruction
(1) Deconstruct function parameters
Function arguments can be destructively assigned:
function foo([a, b]) {
console.log(a + b);
}
foo([1.2]); / / 3
function bar({x, y}) {
console.log(x, y);
}
foo({x: 1.y: 2}); / / 1. 2
Copy the code
Destruct assignment can be used on the return value of a function:
function getStudentInfo() {
return {
name: 'ZhangSan'.age: 18.scores: {
math: 19.english: 85.chinese: 100}}; }const { name, scores: {math, english, chinese} } = getStudentInfo();
console.log(name, math, english, chinese);
Copy the code
2. Deconstruction in cycles
We can also use object deconstruction when we need object keys in a loop:
const students = [
{
'name': 'ZhangSan'.'grade': 80
},
{
'name': 'LiSi'.'grade': 75
},
{
'name': 'WangWu'.'grade': 95}];for(let {name, grade} of students){
console.log(name, grade);
}
Copy the code
3. Dynamic attribute deconstruction
A lot of times we don’t know the key of an object property, only at runtime. For example, there’s getStudentInfo, which takes a key and returns the corresponding attribute value:
getStudentInfo('name');
getStudentInfo('age');
Copy the code
The argument passed to the getStudentInfo method is dynamic, so it can be written like this:
const getStudentInfo = key= > {
const {[key]: value} = student;
return value;
}
Copy the code
Note that the key must be wrapped in square brackets, otherwise undefined values will appear.
4. Swap variables
One useful feature of array structures is to swap local variables. In general, we use temporary variables to exchange variables:
let width = 300;
let height = 400;
let temp = width;
width = height;
height = temp;
console.log(width, height)
Copy the code
If we use array deconstruction assignment, it becomes very simple:
let width = 300;
let height = 400;
[width, height] = [height, width];
console.log(width, height)
Copy the code
5. Array copy
Arrays can be copied using deconstructed assignment and rest operators:
const rgb = [200.255.100];
const [...newRgb] = rgb;
// equivalent to const newRgb = [... RGB]
console.log(newRgb)
Copy the code