Home >Web Front-end >JS Tutorial >Javascript destructuring in ES6

Javascript destructuring in ES6

coldplay.xixi
coldplay.xixiforward
2020-10-27 17:34:322295browse

Todayjavascript column introduces Javascript deconstruction in ES6.

Javascript destructuring in ES6

The destructuring feature in ES6 makes it more convenient for us to get values ​​from objects (Object) or arrays (Array), and the code written out is also readable. Sexually stronger too. Friends who have been exposed to the python language before should be familiar with this. This feature has already been implemented in python. In python, we can use the following code to get the value of the two variables

lst = [3, 5]
first, second = lst 
print(first, second)复制代码

first and second, which are assigned to 3 and 5 in the array respectively. Isn’t it very simple and clear?

Before this feature was available, how did we usually get values ​​from objects or arrays? Let’s take a look at the following code:

let list = [3, 5]let first = list[0]let second = list[1]复制代码

In this method, you must manually specify an array subscript to assign the corresponding value to the variable you specify. If you use the destructuring feature of ES6, the code will become simpler and more readable:

let [first, second] = list;复制代码

Destructuring of objects

Destructuring of basic objects

First we Let’s take a look at how to write basic object destructuring in ES6:

const family = {	father: ''
	mother: ''}const { father, mother } = family;复制代码

We deconstructed its two attributes, father and mother, from the family object, and assigned them to the separately defined father and mother objects. After that, we can directly obtain the value of the corresponding key in the family through the father and mother variables. This example is the simplest application of destructuring objects. Let's take a look at more interesting ones.

Destructuring undeclared objects

In the above example, we first declare the family object, and then obtain the value through destructuring syntax. So is it okay if you don’t declare it:

const { father, mother } =  {father: '',mother: ''}复制代码

It’s actually okay. In some cases, we don’t need to declare an object or assign the object to a variable and then deconstruct it. Many times we can deconstruct undeclared objects directly.

Deconstruct the object and rename the variable

We can also deconstruct the properties in the object and rename them, such as:

const { father: f, mother:m } =  {father: '1',mother: '2'}console.log(f); // '1'复制代码

In the above code, the object After the father in is deconstructed, it is reassigned to the variable f. Compared with the previous example, it is equivalent to renaming the father variable to f. Then you can use f to continue the operation.

Destructuring the default value

Imagine a scenario where a family object is returned in the background. The original family object has three attributes, namely father, mother, and child. You get the returned data and deconstruct these three attributes:

const { father, mother, child } =  {father: '1',mother: '2', child: '3'}复制代码

This seems to be no problem, but the reality is always unsatisfactory. Due to a bug in the code in the background, the returned family object only contains mother and child, but father is missing. At this time, after the deconstruction of the above code, father will become undefined:

const { father, mother, child } =  {father: '1',mother: '2'}console.log(child) //undefined复制代码

Many times we will want to deconstruct a default value when a certain attribute is missing in the background. In fact, you can write it like this:

const { father = '1', mother = '2', child = '3'} =  {father: '1',mother: '2'}console.log(child) //'3'复制代码

Combined with the previous example, you can both change the variable name and assign the default value:

const { father: f = '1', mother: m = '2', child: c = '3'} =  {father: '1',mother: '2'}复制代码

Deconstruct in the function parameter

const family = {	father: ''
	mother: ''}function log({father}){	console.log(father)
}
log(family)复制代码

In Among the parameters of the function, the attribute values ​​of the incoming and outgoing objects can be directly obtained using destructuring, without the need to use family.father to pass them in as before.

Deconstructing Nested Objects

In the above example, the attributes of family only have one level. If the value of some attributes of family is also an object or array, then how to nest them? How about deconstructing the object's attribute values? Let’s take a look at the following code:

const family = {	father: 'mike'
	mother: [{		name: 'mary'
	}]
}const { father, mother: [{	name:motherName
}]} = family;console.log(father); //'mike'console.log(motherName) //'mary'复制代码

Destructuring of arrays

The destructuring method of arrays is actually very similar to that of objects. It was also mentioned slightly at the beginning of the article, but let’s take a look at arrays. Some typical scenes of deconstruction.

Basic object deconstruction

const car = ['AUDI', 'BMW'];const [audi, bmw] = car;console.log(audi); // "AUDI"console.log(bmw); // "BMW"复制代码

As long as the corresponding array position is used, the corresponding value can be correctly deconstructed.

Destructuring default value

Similar to the default value scenario of object destructuring, many times we also need to add default values ​​when deconstructing arrays to meet business needs.

const car = ['AUDI', 'BMW'];const [audi, bmw, benz = 'BENZ'] = car;console.log(benz); // "BENZ"复制代码

Exchanging variables in deconstruction

Suppose we have the following two variables:

let car1 = 'bmw';let car2 = 'audi'复制代码

If we want to exchange these two variables, the past approach is:

let temp = car1;
car1 = car2;
car2 = temp;复制代码

needs to be implemented with the help of an intermediate variable. It is much simpler to use the destructuring of the array:

let car1 = 'bmw';let car2 = 'audi'[car2, car1] = [car1, car2]console.log(car1); // 'audi'console.log(car2); // 'bmw'复制代码

If you want to complete the exchange of element positions within an array, for example, exchange [1,2,3] for [1,3,2], then It can be implemented like this:

const arr = [1,2,3];
[arr[2], arr[1]] = [arr[1], arr[2]];console.log(arr); // [1,3,2]复制代码

Deconstruct the array returned from the function

Many functions will return array type results, and the value can be obtained directly through array destructuring:

functin fun(){	return [1,2,3]
}let a, b, c; 
[a, b, c] = fun();复制代码

Of course, if We only want the function to return some of the values ​​in the array, so we can ignore them

functin fun(){	return [1,2,3]
}let a, c; 
[a, , c] = fun();复制代码

As you can see, the destructuring feature of ES6 is very useful in many scenarios. I hope that everyone can apply more deconstruction to projects to make the code simpler, clearer and easier to understand.

Related free learning recommendations: javascript (Video)

The above is the detailed content of Javascript destructuring in ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete