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 practical skill of JavaScript deconstructing assignment

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article analyzes "what is the practical skill of JavaScript deconstructing assignment". The content is detailed and easy to understand. Friends who are interested in "what are the practical skills of JavaScript deconstruction assignment" can follow the editor's train of thought to read it slowly and deeply. I hope it will be helpful to you after reading. Let's follow the editor to learn more about "what are the practical skills of JavaScript deconstruction assignment".

I. basic concepts

Why do you need to deconstruct? let's first look at an example:

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)

Writing in this way can also achieve the desired results, but the code looks redundant. Also, if the object is deeply nested, the access chain of the object becomes very long. While this is not a big deal, using deconstruction assignments makes the code easier and easier to read.

Let's take a look at what deconstruction assignment is. Description of deconstruction assignment in MDN:

The deconstructing assignment syntax is a Javascript expression. By deconstructing the assignment, you can take the attribute value from the object / array and assign it to other variables.

In fact, structure assignment is to decompose a complex structure into simple parts. Deconstructing assignment syntax can be used for variable declaration or variable assignment. In addition, you can use nested deconstruction assignment syntax to deal with nested structures.

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);}

Doesn't this look much more concise?

2. Deconstruction classification

According to MDN's definition of deconstruction assignment, we can divide deconstruction assignment into two categories:

Object deconstruction

Array deconstruction

Let's take a look at these two deconstruction assignments respectively.

1. Deconstruction assignment of object

Object deconstruction, also known as object attribute allocation mode, allows us to assign the attribute values of the object to the 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)

The first (line 3) is the complete form of object deconstruction, in which each attribute of the object is assigned a variable, in which the property in the source object is preceded by the colon and the attribute to be assigned after the colon

The second (line 5) is an abbreviated form of object deconstruction, which can be used when the object's properties are consistent with the properties to be assigned.

If you need to assign a value to an existing variable, you need to pay extra attention to:

Let obj = {x: 1, y: 2, z: 3}; let x = 0, y = 0, z = 0; ({x, y, z} = obj) console.log (x, y, z)

It should be noted here that the assignment expression needs to be enclosed in parentheses. If omitted, the deconstructed object will be treated as a block statement, and the block statement cannot be placed on the left side of the assignment expression.

When using deconstruction assignments, you can pass a default value to the variable:

Const person = {name: 'ZhangSan', height: 180}; const {name, height, age = 25} = person;console.log (name, height, age)

Here we assign a default value to age, and when the age attribute does not exist on the source object, age is assigned the default value of 25 instead of undefined.

If the assigned object property is undefined, the default value is used:

Const {x = 2} = {x: undefined}; console.log (x); / / 22. Deconstruction assignment of array

When using array deconstruction, you actually use iterators to separate the required values from the structure source. Therefore, we can use array structures for iterable values, including strings, arrays, collections, function mappings, and DOM elements. We can also use deconstruction assignments in conjunction with extension operators.

(1) string let message = 'Hello';let [a, b] = message;let [x, y,... z] = message;console.log (a, b); / / H econsole.log (x, y, z); / / He [' lags, 'lags,' o'] (2) array let numbers = [1, 2, 3]; let [x, y, z] = numbers;console.log (x, y, z) / / 1 23 (3) set let set = new Set (). Add ('foo'). Add (' bar'); let [a, b] = set;console.log (a, b); / / foo bar (4) Maplet map = new Map (). Set ('asides, 1). Set (' baked, 2); let [x, y] = map;console.log (x, y); / / [a ", 1] [" b ", 2]

In the deconstruction of an array, each variable in the array in which the variable is stored is mapped to the corresponding item at the same index on the destructed array.

If an item in the deconstruction is not needed, you can use a comma operator to separate it:

Const rgb = [200,255,100]; const [, blue] = rgb;console.log (blue); / / 100

As with object deconstruction, you can use array deconstruction to set default values for local variables:

Const rgb = [200]; const [red = 255, green, blue = 255] = rgb;console.log (`R: ${red}, G: ${green}, B: ${blue} `)

If the variable already exists, you can write:

Let red = 100,200 green = 200,255,100]; [red, green] = rgb;console.log (`R: ${red}, G: ${green}, B: ${blue} `)

Unlike object deconstruction, there is no need for parentheses to enclose the array.

If the value assigned to the variable is undefined, the default value is used:

Const [x = 1] = [undefined]; console.log (x); / / 1

The default value here is not necessarily 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); / / 2let {x=foo ()} = obj2;console.log (x); / / 1

If we want to assign some elements of the array to variables, and assign 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"] III. Nested deconstruction

The deconstruction knowledge we mentioned above is ordinary arrays and objects. In fact, deconstructing assignments can be used for nested arrays and nested objects. For example, in the example at the beginning of the article, there are deconstructed nested objects:

Const student = {name: 'ZhangSan', age: 18, scores: {math: 19, english: 85, chinese: 100}}; const {name, scores: {math, english, chinese}} = student

Let's take a look at an example of nested array deconstruction:

Let numbers = [1, [2, 3, 4], 5]; let [a, [b, c, d], e] = numbers;console.log (a, b, c, d, e); / / 12345 4, use skill 1. Function deconstruction (1) deconstructing function parameters

You can use deconstruction assignments on function parameters:

Function foo ([a, b]) {console.log (a + b);} foo ([1,2]); / / 3function bar ({x, y}) {console.log (x, y);} foo ({x: 1, y: 2}); / / 12

You can use deconstruction assignments on function return values:

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); 2. Deconstruction in cycles

When we need the object key value in the loop, we can also use object deconstruction:

Const students = [{'name':' ZhangSan', 'grade': 80}, {' name': 'LiSi',' grade': 75}, {'name':' WangWu', 'grade': 95}]; for (let {name, grade} of students) {console.log (name, grade);} 3. Dynamic attribute deconstruction

Most of the time we don't know the key of object properties, but only at run time. For example, there is a method getStudentInfo that takes a key as a parameter and returns the corresponding property value:

GetStudentInfo ('name'); getStudentInfo (' age')

The parameters passed to the getStudentInfo method here are dynamic, so you can write like this:

Const getStudentInfo = key = > {const {[key]: value} = student; return value;}

It is important to note that the square brackets that wrap the key cannot be reduced, otherwise an undefined value will appear.

4. Exchange variable

A very practical function of array structure is to exchange local variables. Usually, we use temporary variables to exchange variables:

Let width = 300 height = 400 BT let temp = width;width = height;height = temp;console.log (width, height)

If you use the deconstruction assignment of an array, it becomes very simple:

Let width = 300 height height = 400; [width, height] = [height, width]; console.log (width, height) 5. Array copy

You can use deconstructing assignments and rest operators to copy an array:

Const rgb = [200,255,100]; const [... newRgb] = rgb;// is equivalent to const newRgb = [... rgb] console.log (newRgb) 4. Deconstruction assignment points

To prevent fetching an object with a value of undefined from the array, you can preset default values for any object in the array to the left of the expression.

When the variable is defined or the value of the variable is set to undefined, null,''and false are all worthwhile in the process of variable parsing, so our default assignment will not be successful.

Examples are as follows:

Const {a = '1percent, b =' 2percent, c = '3percent, d =' 4percent, e ='5'} = {a:'a, b: null, c: undefined, d: false, e:'} console.log (a); / / aconsole.log (b); / / nullconsole.log (c); / / 3console.log (d); / / falseconsole.log (e); / / ""

If you only bind default values based on the existence of attributes, you can use deconstruction assignments.

What is JavaScript? JavaScript is a literal scripting language whose interpreter is called JavaScript engine and is a part of the browser. JavaScript is a scripting language widely used on the client side. It was first used on HTML pages to add dynamic functions to HTML pages.

So much for sharing the practical skills of JavaScript deconstruction assignment. I hope the above content can improve everyone. If you want to learn more knowledge, please pay more attention to the editor's updates. Thank you for following the website!

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