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

How to use the decoupling assignment of variables with new features of JS ES

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you how to use the decoupling assignment of the variables of JS ES's new features. I hope you will get something after reading this article. Let's discuss it together.

1. Decoupling assignment of array

1.1 what is the array decoupling assignment

ECMAScript 2015 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called decoupling assignment.

The way variables were assigned before ECMAScript 2015 is as follows:

Let a = 1% let b = 2 * * let c = 3

In ECMAScript 2015, it is allowed to write as follows.

Let [a, b, c] = [1,2,3]

The decoupling assignment of ECMAScript 2015 is essentially a pattern match. The pattern on both sides of the assignment operator is the same, and the variable on the left is assigned the value of the corresponding position.

1.2 array decoupling assignment failed

If the decoupling assignment fails, the value of the variable is equal to undefined. The sample code is as follows:

/ / if the variable at the position of an index value of an array does not have a corresponding index value in the array to the right of the = operator, the decoupling assignment fails with the value of undefinedlet [v] = [] let [a, b] = [1] console.log (v, a, b); / / undefined 1, undefined

If you want to solve the problem of decoupling assignment failure, you need to keep the number of the left and right sides of its assignment operator the same.

1.3 incomplete decoupling assignment

The so-called incomplete decoupling assignment means that the number of the right array of the assignment operator is larger than that of the left array, resulting in the invalidation of some variables in the right array, but in this case the decoupling assignment will be successful.

The sample code is as follows:

/ / the number of variables on the left side of the assignment operator is less than that on the right side of the operator let [a, b, c] = [1, 2, 3, 4] / / will still decouple the assignment successfully console.log (a, b, c); / / 1231.4 default value

Decoupling assignment allows you to specify a default value. The sample code is as follows:

/ * the default value can be specified in the decoupling assignment * the syntax structure is as follows * let [var1 = value1, var2 = value2,...] = [val1, val2,...] Var1,var2 indicates the variable name value1,value2 represents the default value val1,val2, and indicates the specified value * / let [a = 1, b = 2] = [100] console.log (a, b); / / 100 2

One thing to note when using default values is that ECMAScript6 internally uses the all-equal = = operator to determine whether the value at the specified location is all equal to undefined. The default value takes effect only when it is all equal to undefined.

The test code is as follows:

Let [a = 1, b = 2] = [100, undefined] console.log (a, b); / / 100 2

When we use a null value, although null is also represented as empty, null! = = undefined. So our default value will not take effect.

The test code is as follows:

Let [a = 1, b = 2] = [100,100] console.log (a, b); / 100 null1.5 array decoupling assignment complexity

Because JavaScript is a weakly typed language, any type to the right of the assignment sign is allowed, so the following special cases occur:

Case 1: to the right of the operator is a function. The sample code is as follows

/ / 1. To the right of the operator is a function let [a, b] = [1, function () {return 10;}] console.log (b ()); / / 10

Case 2: to the right of the operator is an object. The sample code is as follows

/ / 2. To the right of the operator is an object let [a, b] = [1, {name: 'Fox Spirit Matchmaker'}] console.log (b); / {name: 'Fox Spirit Matchmaker'}

Case 3: an array of functions to the right of the operator. The sample code is as follows

/ / 3. To the right of the operator is the array let [a, b] = [1, [2, 3]] console.log (b); / / [2, 3]

Case 4: there are arrays on both the left and right sides of the operator. The sample code is as follows

/ / 4. There are arrays on both the left and right sides of the operator. The example code is let [a, [b, c]] = [1, [2,3]] console.log (b); / / 22. Decoupling assignment of object

The decoupling assignment of the object is realized through the one-to-one correspondence between the variable name and the attribute name of the object. The sample code is as follows:

/ * decoupling assignment of objects-extract values from objects and assign values to variables! The variable name must correspond to the property name of the object, otherwise it will fail. * / let {x, y} = {x: 10, y: 20} console.log (x, y); / / 10 20

It is worth noting that the format on both sides of the assignment operator needs to be consistent.

2.1 Special case of object decoupling assignment

Because JavaScript is a weakly typed language, any type to the right of the assignment sign is allowed, so the following special cases occur:

Case 1: to the right of the operator is a function. The sample code is as follows

/ / 1. To the right of the operator is a function let {a, b} = {a: 1, b: function () {return 10;}} console.log (b ()); / / 10

Case 2: to the right of the operator is an object. The sample code is as follows

/ / 2. To the right of the operator is an object let {a, b} = {a: 1, b: {name: 'ywanzhou'}} console.log (b); / {name:' ywanzhou'}

Case 3: an array of functions to the right of the operator. The sample code is as follows

/ / 3. To the right of the operator is the array let {a, b} = {a: 1, b: [1,2]} console.log (b); / / [1,2]

Case 4: both the left and right sides of the operator contain objects, and the sample code is as follows

/ / 4. The operator contains objects let {m: {name, age}, n} = {m: {name: 'test', age: 20}, n: 20} console.log (name, age); / / test 202.2 decoupling assignment failed

If the decoupling assignment fails, the value of the variable is equal to undefined. The sample code is as follows:

/ / decoupling assignment failed let {a, b} = {a: 10} console.log (b); 2.3incomplete decoupling assignment

The so-called incomplete decoupling assignment means that the number of attributes in the right object of the assignment operator is greater than that in the left object, resulting in the invalidation of some variables of the attributes in the right object, but in this case the decoupling assignment will be successful.

/ / incomplete decoupling assignment let {a} = {a: 10, b: 20} console.log (a); 2.4 default

Decoupling assignment allows you to specify a default value. The sample code is as follows:

/ / default value let {a, b = 100} = {a: 10, b: 20} console.log (b); 3. Decoupling assignment of strings, numeric values, and Boolean values

3.1 string decoupling assignment

Strings can also deconstruct assignments. This is because at this point, the string is converted into an array-like object.

Let [H2, y, x] = "one bowl week" console.log (H2, y, x, h3); / / decoupling assignment of 3.2values and Boolean values in a bowl week

If a direct decoupling assignment of a numeric value / Boolean value throws an exception, when operating on a numeric value and a Boolean value, the assignment operator to the right is a numeric value and a Boolean value, it is converted to an object first.

/ / let [a] = 100; / throw exception description information as TypeError: 100 is not iterable// console.log (a); / / if a pair of Boolean or numeric values are decoupled, it needs to be changed to the object type. Let {toString: B} = 1 toString console.log (b = Number.prototype.toString); / / truelet {console.log: C} = true;console.log (c = Boolean.prototype.toString); / / true

The rule of deconstructing assignment is to convert the value to the right of the equal sign as long as it is not an object or an array. Since undefined and null cannot be converted to objects, both deconstructing and assigning them will result in an error.

4. Decoupling assignment of function

The parameters of a function can also be assigned using deconstruction. The sample code is as follows:

/ use the array function f ([a, b]) {console.log (a, b);} f ([10,20]) / / 1020 function fn / use object function fn ({a, b}) {console.log (a, b);} fn ({a: 10, b: 20}) / / 10 205. The question of parentheses

Decoupling assignment is convenient, but it is not easy to parse. For the compiler, there is no way to know whether an expression is a pattern or an expression from the beginning. It must be parsed to (or cannot parse) an equal sign to know.

The question that arises is what to do if parentheses appear in the pattern. The rule of ECMAScript 2015 is that parentheses should not be used as long as there is a possibility of deconstructing ambiguity.

However, this rule is actually not so easy to identify and quite troublesome to deal with. Therefore, it is recommended that you do not place parentheses in the pattern whenever possible.

5.1 cases where parentheses cannot be used

Parentheses cannot be used in the following three situations

Case 1: variable declaration statement, the sample code is as follows

/ / let [(a)] = [1]; let {x: (C)} = {}; let ({x: C}) = {}; let {(x: C)} = {}; let {(x): C} = {}; let {o: ({p: P})} = {o: {p: 2}}

The above six statements all report errors because they are variable declaration statements and patterns cannot use parentheses.

Case 2: as a function parameter

Function parameters are also variable declarations, so you cannot have parentheses.

/ / error function f ([(z)]) {return z;} / / error function f ([z, (x)]) {return x;}

Case 3: the mode of the assignment statement

/ / all errors ({p: a}) = {p: 42}; ([a]) = [5]

The above code places the entire pattern in parentheses, resulting in an error.

/ / error [({p: a}), {x: C}] = [{}, {}]

The above code places part of the pattern in parentheses, resulting in an error.

5.2 cases where parentheses can be used

There is only one case in which parentheses can be used: for the non-modal part of an assignment statement, you can use parentheses.

[(B)] = [3]; / correct ({p: (d)} = {}); / correct [(parseInt.prop)] = [3]; / / correct

The above three lines of statements are executed correctly because, first of all, they are assignment statements, not declaration statements; second, none of their parentheses are part of the pattern. In the first line of statements, the pattern takes the first member of the array, independent of parentheses; in the second line of statements, the pattern is p, not d; and the nature of the third line of statements is the same as that of the first line of statements.

6. The use of variable decoupling assignment

Variable decoupling assignments are useful in many ways. Here are a few common examples.

6.1 swap the values of variables

If you do not decouple the assignment swap variable with the help of a third variable, the sample code is as follows:

Var a = 10, b = 20 var c = a * a = bb = null / release variable console.log (a, b); / / 20 10

With variable decoupling assignment, the sample code is as follows:

Let a = 10, b = 20; [a, b] = [b, a] console.log (a, b); / / 20 10

Using this method is not only concise, but also easy to read and clear semantics.

6.2 return multiple values from a function

The function can return only one value, and if you want to return multiple values, you can only return them in an array or object. With deconstruction assignments, it is very convenient to take out these values.

The sample code is as follows:

/ return an array function example () {return [1,2,3];} let [a, b, c] = example (); / / return an object function example () {return {foo: 1, bar: 2};} let {foo, bar} = example (); 6.3Definitions of function parameters

Deconstructing assignments can easily correspond a set of parameters to variable names.

/ parameters are a set of ordered values function f ([x, y, z]) {console.log (x, y, z);} f ([1, 2, 3]); / / 1 23 JSON / parameters are a set of disordered values function fn ({x, y, z}) {console.log (x, y, z);} fn ({z: 3, y: 2, x: 1}); / / 1236.4 extract JSON data

Deconstructing assignments is particularly useful for extracting data from JSON objects.

/ / extract json data let jsonData = {id: 42, status: "OK", data: [867,5309]}; let {id, status, data: number} = jsonData;console.log (id, status, number) / / 42, "OK", [867, 5309] after reading this article, I believe you have a certain understanding of "how to use the decoupling assignment of variables with new features of JS ES". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!

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