Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
An overview of the
Deconstructing assignment is an extension of the assignment operator. It is a method of pattern matching for arrays or objects, and then assigning values to the variables in them. Concise and easy to read in code writing, more clear semantics; It also facilitates data field retrieval in complex objects.
- Destruct assignment of arrays
- Object destructuring assignment
- Destruct assignment of a string
- Destruct assignment of function arguments
- Parenthesis problem
- use
Destruct assignment of arrays
Basic usage
ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern called Destructuring. Previously, to assign a value to a variable, you had to specify a value directly.
let a = 1;
let b = 2;
let c = 3;
Copy the code
ES6 allows you to write it like this.
let [a, b, c] = [1, 2, 3]; Array deconstruction assignment: it is the operation of extracting values from the array and assigning values to variables according to the corresponding position of the left and right sides of the equal sign. Essentially, this is "pattern matching," in which the variable on the left is assigned a corresponding value as long as the pattern on both sides of the equal sign is the same.Copy the code
Case Study:
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
let [ , , third] = ["foo", "bar", "baz"];
third // "baz"
let [x, , y] = [1, 2, 3];
x // 1
y // 3
Copy the code
If the deconstruction fails, the value of the variable is equal to undefined.
let [foo] = [];
let [bar, foo] = [1];
Copy the code
Incomplete deconstruction, in which the pattern to the left of the equals sign matches only part of the array to the right of the equals sign. In this case, deconstruction can still succeed.
let [x, y] = [1, 2, 3];
x // 1
y // 2
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
Copy the code
If the right-hand side of the equals sign is not an array (or, strictly speaking, not a traversable structure), an error will be reported.
// let [foo] = 1; let [foo] = false; let [foo] = NaN; let [foo] = undefined; let [foo] = null; let [foo] = {}; Iterator interface: an Iterator object that provides a unified access mechanism for a variety of data structures. The data structures that natively have the Iterator interface are as follows. Array Map Set String TypedArray function arguments NodeList objectCopy the code
The default value
-
Destruct assignment allows you to specify default values.
-
let [foo = true] = []; foo // true let [x, y = 'b'] = ['a']; // x='a', y='b' let [x, y = 'b'] = ['a', undefined]; // x='a', y='b' Copy the code
-
Note that ES6 internally uses the strict equality operator (===) to determine whether a position has a value. Therefore, the default value is valid only if an array member is strictly equal to undefined.
-
let [x = 1] = [undefined]; x // 1 let [x = 1] = [null]; x // null Copy the code
-
If the default value is an expression, the expression is lazy, that is, evaluated only when it is used.
-
function f() { console.log('aaa'); } let [x = f()] = [1]; Copy the code
Three-point operator
Symbol:... // To expand the array a into arR, you can use... Let a = [1,2,3,4,5,6]; Let arr = [' aa ', 'bb', 'cc',... a] arr / / [' aa ', 'bb', 'cc', 6] 2. Let [a,b,c...d] = [1,2,3,4,5,6,7,8,9,10]; let [a,b,c...d] = [1,2,3,4,5,6,7,8,9,10]; A //1 b //2 c //3 d //[4,5,6,7,8,9,10]Copy the code
Object destructuring assignment
Basic usage
Deconstruction can be applied to objects as well as arrays. Object deconstruction differs from arrays in one important way. The elements of an array are arranged in order, and the value of a variable is determined by its position. The attributes of an object have no order, and variables must have the same name as the attributes to get the correct value.
Array deconstruction assigns values according to positional correspondence, and object deconstruction assigns values according to key-value pairs
let {name:myname,age:myage,sex:mysex} = {name:'lisi',age:25}
myname //lisi
myage //25
mysex //undefined
Copy the code
Object deconstruction assignment, it is very convenient to assign the method of an existing object to a variable.
let {log:log,dir:dir} = console; // Destruct the console object's method log(console output information) /dir(show all properties and methods under an object) to log and the dir variable console.log(' XXX '); Equivalent to the log (' XXX '); console.dir(window); Equivalent to the dir (Windows); let ? = Math; ? How to write the partCopy the code
Destructuring assignment of an object can be shorthand for the following form (see chapter Extension of Objects)
let { foo: foo, bar: bar } = { foo: 'aaa', bar: 'bbb' };
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
Copy the code
Like arrays, deconstruction can also be used for nested structured objects
Let obj = {list: [' aa ', 'bb', 'cc'], hobby: {ball: [' basketball ', 'football', 'table tennis']. Fruits: [' durian ', 'passion fruit', 'carambola]}} let {list, hobby, list: [a, b, c]} = obj list / / [' aa', 'bb', 'cc'] hobby / / {ball: [' basketball ', 'football', 'table tennis'], fruits: [' durian', 'passion fruit', 'carambola]} a / / aa/b/c/bb/ccCopy the code
The default value
Object deconstruction can also specify default values, which are valid only if the object’s property value is strictly equal to undefined.
let {x,y=20} = {x:10}
x//10
y//20
var {x = 3} = {};
x // 3
var {x, y = 5} = {x: 1};
x // 1
y // 5
var {x = 3} = {x: undefined};
x // 3
var {x = 3} = {x: null};
x // null
Copy the code
Pay attention to the point
(1) If you want to use a declared variable to destruct an assignment, you must be very careful.
// let x; {x} = {x: 1}; // SyntaxError: syntax error //right let {x} = {x:1}Copy the code
The above code is written incorrectly because the JavaScript engine interprets {x} as a block of code, resulting in syntax errors. The only way to solve this problem is to not put curly braces at the beginning of the line and avoid JavaScript interpreting them as blocks of code.
// let x; ({x} = {x: 1}); let x; . . . ({x} = obj);Copy the code
The above code puts the entire destruct assignment statement in parentheses and executes correctly. See below for the relationship between parentheses and deconstructed assignment.
(2) Destruct assignment allows no variable names to be placed in the pattern to the left of the equal sign. As a result, you can write really weird assignment expressions.
({} = [true, false]);
({} = 'abc');
({} = []);
Copy the code
The above expression makes no sense, but the syntax is legal and can be executed.
(3) Because the nature of the array is a special object, so we can deconstruct the object attributes of the array.
let arr = [1, 2, 3]; Let {0: first, [arr. Length - 1] : last} = arr; first // 1 last // 3Copy the code
The above code deconstructs the array object. [arr. Length-1] = 2; [arr. Length-1] = 3; Square brackets are “attribute name expressions” (see extension of Objects).
Destruct assignment of a string
Strings can also deconstruct assignments. This is because at this point, the string is converted to an array-like object.
const [a, b, c, d, e] = 'hello'; 'hello' == ['h','e','l','l','0']
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
Copy the code
Array-like objects have a length attribute, so you can also deconstruct and assign to this attribute.
let {length : len} = 'hello'; Len // 5 // parse 'hello' let hello = {length: 5} let {length:len} = hello;Copy the code
Destruct assignment of function arguments
Function arguments can also be destructively assigned.
function add([x, y]){ return x + y; } add([1, 2]); // 3 [[1, 2], [3, 4]].map(([a, b]) => a + b); // [3, 7] Function arguments can also be destructed using default values. function add([x, y=10]){ return x + y; } add([1]); // 11 function move({x = 0, y = 0} = {}) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, 0] move({}); // [0, 0] move(); / / [0, 0]Copy the code
Parenthesis problem
While deconstructing assignments is convenient, it’s not easy to parse. There is no way for the compiler to know from the start whether an expression is a pattern or an expression. It must be parsed to (or not) the equals sign.
This raises the question of what to do if parentheses are present in the schema. The rule of ES6 is that parentheses should not be used whenever there is a possibility of ambiguity about deconstruction.
However, this rule is actually not so easy to discern and can be quite troublesome to deal with. Therefore, it is recommended that parentheses not be placed in schemas whenever possible.
let {(x)} = {x:1}
Copy the code
use
Destructive assignment of variables has many uses.
(1) Exchange the values of variables
let x = 1;
let y = 2;
[x, y] = [y, x];
Copy the code
The above code exchanges the values of variables X and y, which is not only concise, but also easy to read, semantic very clear.
(2) Return multiple values from the function
The function can return one value. If you want to return multiple values, you must return them in arrays or objects. With deconstructing assignments, it’s very convenient to pull out these values.
Function example() {return [1, 2, 3]; } let [a, b, c] = example(); Function example() {return {foo: 1, bar: 2}; } let { foo, bar } = example();Copy the code
(3) Definition of function parameters
Destructuring assignments makes it easy to map a set of parameters to variable names.
Function f([x, y, z]) {function f([x, y, z]) {... } f([1, 2, 3]); Function f({x, y, z}) {... function f({x, y, z}) {... } f({z: 3, y: 2, x: 1});Copy the code
(4) Extract JSON data
Destructuring assignments is especially useful for extracting data from JSON objects.
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
Copy the code
The code above can quickly extract the value of the JSON data.
(5) Default values of function parameters
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
} = {}) {
// ... do stuff
};
Copy the code
The default value of the specified argument, avoids the within the function body to write var foo = config. The foo | | ‘default foo’; Statement like this.
(6) Traverse the Map structure
You can use for any object that has the Iterator interface deployed. The of loop traverses. The Map structure natively supports the Iterator interface, and it is very convenient to obtain key names and values along with the deconstructive assignment of variables.
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world
Copy the code
If you just want to get the key name, or if you just want to get the key value, you can write it like this.
For (let [key] of map) {//... } for (let [,value] of map) {//... }Copy the code
(7) The specified method of input module
When a module is loaded, it is often necessary to specify which methods to input. Deconstructing assignment makes the input statement very clear.
const { SourceMapConsumer, SourceNode } = require("source-map"); // Load in an object, essentially a deconstructed assignment of the objectCopy the code