Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the meaning of es6 deconstruction?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "what is the meaning of es6 deconstruction". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the meaning of es6 deconstruction".

In es6, deconstruction refers to the behavior of extracting values from arrays and objects and assigning variables according to a certain pattern; there are object structure, array deconstruction and mixed deconstruction, which is a process of decomposing the data structure into smaller parts, so as to simplify the extraction of information.

This tutorial operating environment: windows10 system, ECMAScript version 6. 0, Dell G3 computer.

What does the deconstruction of es6 mean?

Destructuring: Baidu encyclopedia means structural decomposition. ES6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called Destructuring.

Object deconstruction, array deconstruction and mixed deconstruction are common in development. This is a process of decomposing the data structure into smaller parts, so as to simplify the extraction of information.

Object deconstruction

Traditional methods to get values in an object

Let node = {type: 'Identifier', name:' foo'} console.log (node.type) / / Identifierconsole.log (node.foo) / / foo

Use deconstruction

Let node = {type: 'Identifier', name:' foo'} let {type, name} = nodeconsole.log (type) / / Identifierconsole.log (name) / / foo

If the specified local variable name does not exist in the object, the local variable is assigned to undefined

Let {type, name, value} = nodeconsole.log (type) / / Identifierconsole.log (name) / / fooconsole.log (value) / / undefined

When the specified attribute does not exist, you can define any default value for the attribute that does not exist.

Let {type, name, value = true} = nodeconsole.log (type) / / Identifierconsole.log (name) / / fooconsole.log (value) / / true

Specify a new variable name for deconstruction assignment

Let arr = {six: 'male', age: 19} let {six:newSix, age:newAge} = arrconsole.log (six, age) / / six is not definedconsole.log (newSix, newAge) / / male 19

Look at the above is not very strange, the traditional object assignment is the left four attributes, the right is the value. But in deconstruction, there are attributes on the right and values on the left, so the new variable name is on the right.

If you use let, var, const to deconstruct the object, the value of the deconstructed object must exist.

When you do not use var, let or const assignments, you need to wrap the deconstruction statement with ()

({type,name} = node); / / {} as a code block in js, adding an equal sign alone will result in an error.

Nested object deconstruction

In the deconstruction of object nested objects, we will continue to use curly braces in the first layer of deconstruction to drill down to the next level; let's first look at a chestnut:

Let node = {type: "Identifier", name: "foo", loc: {start: {line: 1, column: 1}, end: {line: 1, column: 4}

Above is a nested object node. Let's deconstruct the first layer first.

Let {loc, type, name} = node / / {} Identifier foo

We can see that we deliberately upset the order of the attributes in {}, and the results are still output correctly, so we can guess that the specific corresponding way should be based on the name, regardless of the order.

Continue to deconstruct the second layer

Let {loc: {start}} = node;console.log (start.line); / / 1console.log (start.column); / / 4

Here we can also assign start to a new custom local variable, assuming we assign a value to newStart

Let {loc: {start: newStart}} = nodeconsole.log (newStart.line) / / 1console.log (newStart.column) / / 4

The summary is as follows:

All identifiers before colons represent the retrieval location in the object, with the name of the variable being assigned to the right; if the colon is followed by curly braces, it means that the final value to be assigned is nested in a deeper hierarchy within the object.

Array deconstruction

Array deconstruction uses array literals, and the deconstruction operations are all done within the array, and array deconstruction does not require the use of object naming properties like object literal syntax.

Let colors = ['red',' green', 'blue'] let [firstColor, secondColor] = colorsconsole.log (firstColor) / /' red'console.log (secondColor) / / 'green'

In the array deconstruction syntax, we mainly select the value by its position in the array, and we can store it in any variable, and the undeclared elements will be ignored directly.

Let [, thirdColor] = colorsconsole.log (thirdColor) / / 'blue'

Variable exchange of array deconstruction

In traditional ES5, interchange values generally require the introduction of a third temporary variable as a relay, but if you use array deconstruction assignment syntax, there is no need to add additional variables.

/ / Exchange values in ES5: let a = 1, b = 2, tmp; tmp = an a = b = tmp console.log (a, b) / / 2,1 / / ES6 let a = 1, b = 2; [a, b] = [b, a] console.log (a, b) / / 2,1

Nested data deconstruction

Let colors = ['red', [' green', 'lightgreen'],' blue'] let [firstColor, [secondColor, thirdColor], fourthColor] = colors console.log (firstColor) / / redconsole.log (secondColor) / / greenconsole.log (thirdColor) / / lightgreenconsole.log (fourthColor) / / blue

Default value

You can also add a default value anywhere in the array in the array deconstruction assignment expression, using the default value when the attribute at the specified location does not exist or its value is undefined

Let colors = ['red'] let [firstColor, secondColor =' green'] = colorsconsole.log (firstColor) / / redconsole.log (secondColor) / / green

Indefinite element

... In order to expand the operator, we should all know its purpose, which can be used to expand the array into a string when manipulating the array. In array deconstruction, you can pass. The syntax assigns the rest of the array to a specific variable.

Let colors = ['red',' green', 'blue'] let [firstColor,... restColors] = colorsconsole.log (firstColosr) / /' red'console.log (restColors.length); / / 2console.log (restColors [0]); / / "green" console.log (restColors [1]); / / "blue"

Array replication

In ES5, developers often use the concat () method to clone arrays

Var colors = ["red", "green", "blue"]; var clonedColors = colors.concat (); console.log (clonedColors); / / "[red,green,blue]"

The concat () method is designed to join two arrays and returns a copy of the current function if no arguments are passed when called.

In ES6, the same goal can be achieved through the syntax of indefinite elements

Let colors = ["red", "green", "blue"]; let [... clonedColors] = colors;console.log (clonedColors); / / "[red,green,blue]"

In the deconstructed array, the indefinite element must be the last entry, and adding a comma later will cause the program to throw a syntax error.

Mixed deconstruction let err = {errors: [{msg: 'this is a message'}, {title:' this is a title'}]}

In the above code, the err object contains errors,errors, which is both an array and a new object, extracting the msg from the object. We can deconstruct the above chestnuts step by step:

Let {errors} = errlet [firstArr] = errorslet {msg} = firstArrconsole.log (msg) / / 'this is a message' can also deconstruct let [, {title}] = err.errorsconsole.log (title) / /' this is a title'let [{msg}] = err.errorsconsole.log (msg) / / 'this is a message'

Let's take a look at a more complex one. In fact, as long as you can find the order, this is very simple to understand.

Let node = {type: "Identifier", loc: {start: {line: 1, column: 1}}, range: [0,3]}; let {loc: {start}, range: [startIndex]} = node;console.log (start.line); / / 1console.log (start.column); / / 1console.log (startIndex); / / 0

Actual use-parameter deconstruction

It is generally used to encapsulate function parameters, such as Chestnut:

The attribute on options indicates the additional parameter function setCookie (name, value, options) {options = options | | {}; let secure = options.secure, path = options.path, domain = options.domain, expires = options.expires / / set the code of cookie} / / can be rewritten as follows: deconstruct options and give the default value function setCookie (name, value, {secure, path, domain, expires} = {}) {/ /. Thank you for reading. This is the content of "what is the meaning of es6 deconstruction". After the study of this article, I believe you have a deeper understanding of the meaning of es6 deconstruction. The specific use situation still needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report