We often see multiple return values in other programming languages, such as GO, because there are many practical scenarios where the return value of a function does not have a single value. Prior to ES6, there was no feature to implement multiple return values directly using syntax. ES6 finally has syntactic sugar for deconstructing assignments to solve such problems.
Destruct assignment is an expression that allows you to assign values or attributes of an iterable to variables using arrays or objects. Deconstructing assignments allows us to assign multiple variables with a shorter syntax, greatly reducing the amount of code. There are two types of destructed expressions: array and object.
Today’s article will be introduced from the following aspects:
- Destruct assignments using array expressions
- Regular use
- Ignore some values in the array
- Use expansion syntax
- Default Parameter Value
- Nested array deconstruction
- As a function parameter
- Destruct assignments using object expressions
- Regular use
- Default Parameter Value
- Nested objects
- As a function parameter
- other
- Methods of deconstructing objects
- Get the length of the string
- Split string
- Switching variable
- Traverse the Map structure
- Method to load the specified module
- Common Scenarios
This chapter will take 15 minutes to read
Destruct assignments using array expressions
Regular use
How do I assign an array of values to multiple variables? Array deconstruction syntax allows us to quickly iterate over the elements of an array and assign values to multiple variables.
Before E6, we could assign the contents of an array to multiple variables in this form:
var myArray = [1.2.3];
var a = myArray[0];
var b = myArray[1];
var c = myArray[2];Copy the code
With ES6, we can do this in a single statement by deconstructing the syntax with arrays.
let myArray = [1.2.3];
let a, b, c;
[a, b, c] = myArray; //array destructuring assignment syntaxCopy the code
In the above code, [a, b, c] is the destruct expression. On the left side of the array destruct statement are the variables that need to be assigned, and on the right side of the equals sign are the values that need to be assigned.
We can also make the above code shorter, you can also write it like this:
let [a, b, c] = [1, 2, 3];
Instead of creating variables separately, we create them on the same line. Is it more refreshing?
If the value on the left is less than the number of items in the array on the right, the value of the variable on the left will only correspond to the contents of the array on the right.
Ignore some values in the array
If we only have two variables, we have three items in the array, and we want to skip the second item in the array, how do we use the array to deconstruct assignment? The code is as follows:
let [a, , b] = [1.2.3];
console.log(a);
console.log(b);Copy the code
Above code we use,, ignore the second item in the array, suggest a space in the middle, we can easily read.
Use expansion syntax
The last article “[ES6 Foundation] Spread syntax”, the author introduced several application scenarios of Spread syntax, because the last article did not introduce deconstruction assignment, so here to introduce the application of Spread syntax in deconstruction assignment. The following code looks like this:
let [a, ...b] = [1.2.3.4.5.6];
console.log(a);
console.log(Array.isArray(b));
console.log (b);"Copy the code
The above code will print:
1
true
2.3.4.5.6Copy the code
In the above code, you can see that the b variable is deconstructed and assigned to an array. Here… This is the use of the remaining parameter scenarios we mentioned in the previous article.
If we want to skip some of the values in the array, we can do so, as shown in the following code:
let [a, , ,...b] = [1.2.3.4.5.6];
console.log(a);
console.log(b);Copy the code
The above code will print:
1
4.5.6Copy the code
In this code we skipped the second and third items of the array.
Default Parameter Value
In “[ES6 Basics] Default Parameter Values”, I introduced how to use the default parameter values. In deconstructing assignment, how to set the default values of variables is shown in the following code:
let [a, b, c = 3] = [1.2];
console.log(c); / / the Output "3"Copy the code
Nested array
We can also extract values from multidimensional arrays and assign them to variables, as shown in the following code:
let [a, b, [c, d]] = [1.2[3.4]].Copy the code
As a function parameter
We can also extract the value of an iterable array using an array destruct expression as a function argument, which is passed as an argument to the function argument, as shown in the following code:
function myFunction([a, b, c = 3]) {
console.log(a, b, c); //Output "1 2 3"
}
myFunction([1.2]);Copy the code
We can use structural assignment to provide a set of default values for related variables and pass undefined, as shown in the following code:
function myFunction([a, b, c = 3] = [1.2.3]) {
console.log(a, b, c); //Output "1 2 3"
}
myFunction(undefined);Copy the code
Here, we pass undefined as an argument, so we use the default array [1,2,3] for extraction assignment.
Destruct assignments using object expressions
Regular use
Object destruct assignment assigns the value of an object property to multiple variables. Before ES6 we could assign an object attribute to multiple variables like this:
var object = {name : "John".age : 23};
var name = object.name;
var age = object.age;Copy the code
In ES6, we can use objects to deconstruct expressions and assign values to multiple variables in a single line, as shown in the following code:
let object = {name : "John".age : 23};
let name, age;
({name, age} = object); //object destructuring assignment syntaxCopy the code
To the left of an object’s deconstruction assignment is the expression for the deconstruction assignment, and to the right is the object to assign the assignment. Never leave out the left and right parentheses () around a deconstruction statement, otherwise an error will be reported.
Note that the name of the destruct object variable must be the same as the property name of the object on the right, otherwise the variable will be prompted with undefined. If you want to name the variable with a different name, you can do so, as shown in the following code:
let object = {name : "John".age : 23};
let x, y;
({name: x, age: y} = object);Copy the code
The above code x,y are the values of the corresponding object attribute John,23. If you print name or age, the compiler will say ReferenceError: The variable is not defined
We can make the code shorter, as shown in the following code:
let {name: x, age: y} = {name : "John".age : 23};Copy the code
The above code is on the same line as the declaration variable and the destruct assignment, so there are no open parentheses () around the object destruct statement.
Default Parameter Value
We can provide default values for variables that are not assigned to the destruct object, as shown in the following code:
let {a, b, c = 3} = {a: "1".b: "2"};
console.log(c); / / the Output "3"Copy the code
Variable names support expression evaluation when destructing objects, as shown in the following code:
let {["first"+"Name"]: x} = { firstName: "Eden" };
console.log(x); / / the Output "Eden"Copy the code
Nested objects
We can also extract property values from nested objects, objects within objects. The following code looks like this:
let {name, otherInfo: {age}} = {name: "Eden".otherInfo: {age:23}};
console.log(name, age); //Eden 23Copy the code
As a function parameter
Just like array destruct assignment, we can also use object destruct assignment as a function argument, as shown in the following code:
function myFunction({name = 'Eden', age = 23, profession ="Designer"} = {}){
console.log(name, age, profession); // Outputs "John 23 Designer"
}
myFunction({name: "John".age: 23});Copy the code
Here, we pass an empty object as the default parameter value. If we pass undefined as a function parameter, the variable will use the default value.
other
Methods of deconstructing objects
For example, the method of the structure Math object is shown in the following code:
let {floor,pow}=Math;// Extract the method in Math into a variable
let a=1.1;
console.log(floor(a));/ / 1
console.log(pow(2.3));/ / 8Copy the code
Gets the length of the string
var {length}='lxy';
console.log(length);/ / 3Copy the code
Split string
var [a,b,c,d]='Front-end talent';
console.log(a,b,c,d) // Output: the front endCopy the code
Switching variable
let x = 1;
let y = 2;
[x, y] = [y, x];Copy the code
Traverse the Map structure
var map = new Map(a); map.set('first'.'hello');
map.set('second'.'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}Copy the code
Method to load the specified module
const { SourceMapConsumer, SourceNode } = require("source-map");Copy the code
Common Scenarios
For example, we often interact with data from the back-end API interface, and we need to process the returned JSON object. Using the deconstruction method greatly simplifies our code, as shown in the following code:
let jsonData = {
id: 42.status: "OK".data: [867.5309]};let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]Copy the code
section
Today’s content is a bit more, we must have a comprehensive understanding of deconstruction assignment, using deconstruction assignment is not very powerful, greatly simplifies our code, although the advantage is quite many, but increase the difficulty of understanding the code, we only in practice, to deepen our understanding of deconstruction assignment.
ES6 related articles
ES6 Basics Let and scope
【ES6 basics 】 Const introduction
ES6 Basics Default value
【ES6 分 】 Spread syntax
More exciting content, please pay attention to the wechat “front-end talent” public number!