Parsing the values in the ES6 version of JavaScript-basic knowledge

Source: Internet
Author: User

What is a deconstruction assignment?

The deconstruction assignment allows you to assign array and object property values to a series of variables using syntax such as array or object literal. This syntax is very concise and more explicit than traditional attribute access.

Access the first three items of the array without using the destructor assignment:

var-i = somearray[0];
var second = somearray[1];
var third = somearray[2];
 
var-i = somearray[0];
var second = somearray[1];
var third = somearray[2];

After you use the deconstruction assignment, the corresponding code becomes more concise and readable:

var [A, second, third] = Somearray;
 
var [A, second, third] = Somearray;

SpiderMonkey (Firefox's JavaScript engine) has supported most of the features of the deconstruction assignment, but not quite yet.
the deconstruction assignment of arrays and iterated objects

Above we have seen an example of array deconstruction assignment, the general form of this syntax:

[Variable1, Variable2, ..., variablen] = array;
 
[Variable1, Variable2, ..., variablen] = array;

This assigns the corresponding item in the array to Variable1 to Variablen, and if you need to declare the variable at the same time, you can add the Var,let or const keyword before the deconstruction expression.

var [variable1, Variable2, ..., variablen] = array;
Let [Variable1, Variable2, ..., variablen] = array;
const [Variable1, Variable2, ..., variablen] = array;
 
var [variable1, Variable2, ..., variablen] = array;
Let [Variable1, Variable2, ..., variablen] = array;
const [Variable1, Variable2, ..., variablen] = array;

In fact, you can also nest any depth:

var [foo, [[Bar], Baz]] = [1, [[2], 3]];
Console.log (foo);
1
console.log (bar);
2
Console.log (baz);
3
 
var [foo, [[Bar], Baz]] = [1, [[2], 3]];
Console.log (foo);
1
console.log (bar);
2
Console.log (baz);
3

In addition, you can skip some of the items in several groups:

var [,, Third] = ["foo", "Bar", "Baz"];
Console.log (third);
"Baz"

 
var [,, Third] = ["foo", "Bar", "Baz"];
Console.log (third);
"Baz"

You can also use a rest expression to capture the remaining items in an array:

var [head, ... tail] = [1, 2, 3, 4];
Console.log (tail);
[2, 3, 4]
 
var [head, ... tail] = [1, 2, 3, 4];
Console.log (tail);
[2, 3, 4]

If an array crosses the line or accesses an item that does not exist in the array, it gets the same value as the array index: undefined.

Console.log ([][0]);
Undefined

var [missing] = [];
Console.log (missing);
Undefined
 
console.log ([][0]);
Undefined
 
var [missing] = [];
Console.log (missing);
Undefined

Note that the way the array is refactored is also applicable to the objects that can be traversed:

function* fibs () {
 var a = 0;
 var b = 1;
 while (true) {
  yield A;
  [A, b] = [B, a + b];
 }
}

var [Second, third, fourth, fifth, sixth] = Fibs ();
Console.log (sixth);
5
 
function* fibs () {
 var a = 0;
 var b = 1;
 while (true) {
  yield A;
  [A, b] = [B, a + b];
 }
}
 
var [Second, third, fourth, fifth, sixth] = Fibs ();
Console.log (sixth);
5

The deconstruction assignment of an object

The deconstruction assignment of an object allows you to bind a variable to a different property value of the object. Specifies the name of the property to be bound, followed by the variable to bind:

var Robota = {name: "Bender"};
var ROBOTB = {name: "Flexo"};

var {Name:namea} = Robota;
var {name:nameb} = ROBOTB;

Console.log (NAMEA);
"Bender"
Console.log (NAMEB);
"Flexo"
 
var Robota = {name: "Bender"};
var ROBOTB = {name: "Flexo"};
 
var {Name:namea} = Robota;
var {name:nameb} = ROBOTB;
 
Console.log (NAMEA);
"Bender"
Console.log (NAMEB);
"Flexo"

There is also a syntactic sugar when the property name that is bound is the same as the variable name that receives the property value:

var {foo, bar} = {foo: ' Lorem ', bar: ' Ipsum '};
Console.log (foo);
"Lorem"
Console.log (bar);
' Ipsum '
 
var {foo, bar} = {foo: ' Lorem ', bar: ' Ipsum '};
Console.log (foo);
"Lorem"
Console.log (bar);
"Ipsum"

As with arrays, you can nest:

var complicatedobj = {
 Arrayprop: [
  "Zapp",
  {second: "Brannigan"}
 ]
};

var {arrayprop: [I, {second}]} = Complicatedobj;

Console.log (a);
"Zapp"
Console.log (second);
"Brannigan"
 
var complicatedobj = {
 Arrayprop: [
  "Zapp",
  {second: "Brannigan"}
 ]
};< C28/>var {arrayprop: [I, {second}]} = Complicatedobj;
 
Console.log (a);
"Zapp"
Console.log (second);
"Brannigan"

When you deconstruct a nonexistent attribute, you get undefined:

var {missing} = {};
Console.log (missing);
Undefined
 
var {missing} = {};
Console.log (missing);
Undefined

There is also a potential pitfall when you use an object's deconstruction to assign a value without declaring a variable (no Var, let, or const keyword):

{blowup} = {blowup:10};
Syntax error
 
{blowup} = {blowup:10};
Syntax Error

This is because the JavaScript syntax tells the engine that any statement that starts with {is a statement block (for example, {console} is a valid statement block), and the solution is to wrap the entire statement in parentheses:

({safe} = {});
No errors
 
({safe} = {});
No errors

Other information

When you attempt to deconstruct null or undefined, you will get the type error:

var {blowup} = null;
Typeerror:null has no properties
 
var {blowup} = null;
Typeerror:null has no properties

However, you can deconstruct other basic types (Boolean, String, and number) and get undefined:

var {wtf} = NaN;
Console.log (WTF);
Undefined

 
var {wtf} = NaN;
Console.log (WTF);
Undefined

The results may surprise you, but the reason is very simple. When an object deconstruction assignment is made, the objects that are refactored are cast to object, except for null and undefined, and other types can be cast to objects. When the structure of an array is assigned, the object that is being refactored has an iterator.
Default Value

You can specify a default value for a property that does not exist:

var [missing = True] = [];
Console.log (missing);
True

var {message:msg = "something went wrong"} = {};
Console.log (msg);
"Something went wrong"

var {x = 3} = {};
Console.log (x);
3
 
var [missing = True] = [];
Console.log (missing);
True
 
var {message:msg = "something went wrong"} = {};
Console.log (msg);
"Something went wrong"
 
var {x = 3} = {};
Console.log (x);
3

Practical application
function arguments

As a developer, we often use an object that contains multiple attributes as a function parameter to implement a more flexible API, rather than having the API's users memorize certain sequential parameters. We can use the deconstruction assignment of an object to avoid property access each time the parameter is used:

function removebreakpoint ({URL, line, column}) {
 //...
}
 
function removebreakpoint ({URL, line, column}) {
 //...
}

Configuration Object

To refine the example above, we can provide default values for the object properties to be refactored, which is useful for objects that are configured as parameters because many configuration items have a reasonable default value. For example, the second parameter of the Ajax method of JQuery is a configuration object that we can implement:

Jquery.ajax = function (URL, {
 async = true,
 beforesend = noop,
 cache = True,
 complete = noop,
 cro Ssdomain = False,
 global = True,
 //... more config
} {
 //... do stuff
};
 
Jquery.ajax = function (URL, {
 async = true,
 beforesend = noop,
 cache = True,
 complete = noop,
 cr Ossdomain = False,
 global = True,
 //... more config
} {
 //... do stuff
};

This avoids repetitive code like this: var foo = Config.foo | | Thedefaultfoo;.
used with iterators

When traversing the Map object, we can use the deconstruction assignment to traverse [key, value]:

var map = new map ();
Map.set (window, "the global");
Map.set (document, "the document");

for (var [key, value] of map) {
 Console.log (key + ' is ' + value);
}
"[Object Window] is the global"
//"[Object HTMLDocument] is the document"

 
var map = new map ();
Map.set (window, "the global");
Map.set (document, "the document");
 
for (var [key, value] of map) {
 Console.log (key + ' is ' + value);
}
"[Object Window] is the global"
//"[Object HTMLDocument] is the document"

Traverse Key only:

for (var [key] of map) {
 //...
}

 
for (var [key] of map) {
 //...
}

Only traversal value:
for (var [, value] of map) {
 //...
}

 
for (var [, value] of map) {
 //...
}

Return multiple values

Returns an array that is extracted to the return value by the deconstruction assignment:

function Returnmultiplevalues () {return
 [1, 2];
}
var [foo, bar] = Returnmultiplevalues ();

 
function Returnmultiplevalues () {return
 [1, 2];
}
var [foo, bar] = Returnmultiplevalues ();

Or, returns an object that has a key value pair:

function Returnmultiplevalues () {return
 {
  foo:1,
  bar:2
 };
}
var {foo, bar} = Returnmultiplevalues ();

 
function Returnmultiplevalues () {return
 {
  foo:1,
  bar:2
 };
}
var {foo, bar} = Returnmultiplevalues ();

Both are better than using intermediate variables:

function Returnmultiplevalues () {return
 {
  foo:1,
  bar:2
 };
}
var temp = returnmultiplevalues ();
var foo = Temp.foo;
var bar = Temp.bar;
 
function Returnmultiplevalues () {return
 {
  foo:1,
  bar:2
 };
}
var temp = returnmultiplevalues ();
var foo = Temp.foo;
var bar = Temp.bar;

Adoption of a continuation:

function Returnmultiplevalues (k) {
 K (1, 2);
}
Returnmultiplevalues ((foo, bar) => ...);

 
function Returnmultiplevalues (k) {
 K (1, 2);
}
Returnmultiplevalues ((foo, bar) => ...);

Import the specified portion of the COMMONJS module

Have not used the ES6 module, that at least used Commonjs bar. When importing a COMMONJS module X, the module provides many more methods than you actually use. With the deconstruction assignment, you can explicitly specify which parts of the module you want to use:

const {Sourcemapconsumer, Sourcenode} = require ("Source-map");
 
const {Sourcemapconsumer, Sourcenode} = require ("Source-map");

If you use the ES6 module mechanism, you can see the import declaration with a similar syntax.
Conclusions

We see that the deconstruction assignment is useful in many scenarios. We already have a lot of experience in Mozilla. Lars Hansen introduced the Brendan to Opera more than 10 years ago, and Eich added support for Firefox a little later, first in Firefox 2. Therefore, the deconstruction assignment has penetrated into our daily use of JS, quietly making our code shorter and neater.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.