Destructuring assignment can also be regarded as a characteristic operation of es6. Through a specific mode, extract values from arrays or objects and assign values to variables. This mode is called destructuring assignment.
1. Array destructuring assignment
let [a, b, c] = [6, 8, 9]; console.log(a, b, c) //6 8 9
As mentioned above, this is actually a kind of “pattern matching”, so some of the following scenarios also support deconstruction.
nested array destructuring assignment
let [a, [b, c, [d]], e] = [1, [2, 3, [4]], 5]; console.log(a, b, c, d, e) //1 2 3 4 5
Some elements in the array are destructured and assigned
let [a, , c] = [1, 3, 4] console.log(a, c) //1 4
Destructuring assignment using the spread operator (…)
let [a, ...b] = [1, 2, 3, 4, 5, 6] console.log(a,b) //1 [2, 3, 4, 5, 6]
Insufficient array elements on the right side of the equal sign when destructuring assignment
let [a, b, ... c] = [1]; console.log(a, b, c) //1 undefined []
Incomplete destructuring: When the destructuring assignment only matches some elements on the right side of the equal sign, the destructuring assignment can still succeed
let [a] = [1, 2, 3] console.log(a) //1
It is not difficult to see from the above examples that the requirements for deconstruction assignment are relatively loose.
But if the right side of the equal sign is not a traversable structure, an error will be reported.
In fact, as long as a certain data structure has the Iterator interface, the destructuring assignment in the form of an array can be used. (Whether the destructuring assignment will report an error or not depends on whether it is a data structure with an Iterator interface)
Default value: Destructuring assignment can set a default value. When the array element on the right side of the equal sign === undefined, the default value will take effect.
let [a, b=6, ...c] = [1]; console.log(a, b, c) //1 6 []
‘undefined’ and null obviously cannot ===undefined, so the default value does not take effect
let [a = 3, b = 6, ...c] = ['undefined', null]; console.log(a, b, c) //undefined null []
If the default value is an expression, the expression will only be evaluated when used.
let [a = f()] = []; console.log(a)//6 function f() { console.log('used the default value') //used the default value return 6; }
Default values can also refer to other variables, provided they can only refer to variables that have already been declared.
let [a = 1, b = a] = [] console.log(a, b) //1 1 let [a = b, b = 1] = [] console.log(a, b) //Uncaught ReferenceError: Cannot access 'b' before initialization
2. Object deconstruction assignment
The destructuring assignment of an object is similar to that of an array, but the difference is that the variable name must be the same as the property name in order to get the correct value.
Otherwise, the deconstruction will fail, and the variable value of the deconstruction failure will be equal to undefined.
let {a,b}={a:'555',c:'888'} console.log(a,b) //555 undefined
If the variable name and the object property name are really inconsistent, but we need to use destructuring assignment, we can do this
let {a:b}={a:'666'} console.log(b) //666
So the essence of object destructuring assignment is actually as follows, but the destructuring mode with the same attribute name and variable name as a:a and b:b can be abbreviated as a, b,
If there is no attribute e on the right side of the equal sign, the value cannot be obtained, so the value of e is undefined.
let {a:a,b:b,c:d,e:e}={b:'777',a:'666',c:'999'} console.log(a,b,d,e) //666 777 999 undefined
Like arrays, object deconstruction also supports objects with nested structures. In the following example, the first a is a variable, and the destructured object is the array corresponding to attribute a
And the second a is a deconstruction mode and will not be assigned.
let obj = { a:[ '111', { y: '222' } ] }; let {a,a: [x, {y}]} = obj; console.log(a,x,y) //(2) ['111', {y: '222'}] '111' '222'
Second example of nested object destructuring
const node = { a: { b: { c: 1, d: 2 } } }; let {a,a:{b,b:{c,d} } } = node; console.log(a,b,c,d) //{b:{c: 1, d: 2} } {c: 1, d: 2} 1 2
If the destructuring mode is a nested object, and the parent property where the child object is located does not exist, an error will be reported.
In the following example, the parent attribute a of the object {b} does not exist, and the deconstruction code reports an error
let {a: {b} } = {b:'111', c: '222'}; // Cannot read properties of undefined (reading 'b')
The destructuring assignment of the object can get the inherited properties.
const a = {}; const b = { c:'111' }; Object. setPrototypeOf(a, b); const {c} = a; console.log(c) // "111"
Object destructuring defaults
var {a = 3,b:c=4,d:e=6,f} = {f:2,b:9}; console.log(a,c,e,f)//3 9 6 2
Since arrays are essentially special objects, object properties can be destructured on arrays.
let arr = [1, 2, 3]; let { 0: a, 1: b } = arr; console.log(a,b) //1,2
3. String destructuring assignment
When the string is destructured and assigned, the string is converted into an array-like object, and at the same time, the length property can be destructured and assigned.
const [a, b, c, d, e] = 'jxy666'; console.log(a, b, c, d, e) //j x y 6 6 let {length : len} = 'jxy666'; console.log(len) //6
4. Numeric and Boolean deconstruction
The rule of destructuring assignment is that as long as the value on the right side of the equal sign is not an object or an array, it is first converted to an object
let {toString: a} = 123; console.log(a === Number.prototype.toString) // true let {toString: b} = true; console.log(a === Boolean.prototype.toString) // true
Since undefined and null cannot be converted into objects, an error will be reported if they are deconstructed and assigned
let { prop: x } = undefined; // TypeError let { prop: y } = null; // TypeError
5. Destructuring assignment of function parameters
function add([x, y]) { return x + y; } console.log(add([1, 2])); // 3
Function parameter destructure assignment default value
function move({a = 0,b = 1} = {a:2,b:3}) { console. log(a, b); } move({a: 3,b: 4}); // 3 4 move({a: 3}); //3 1 move({b: 4}); //0 4 move({}); // 0 1 move(); // 2 3
The ES6 rule is that parentheses must not be used whenever there is an ambiguity that could lead to destructuring.
Therefore, it is recommended that parentheses not be placed in patterns whenever possible.
6. Scenarios for Destructuring Assignments
Assignment of swap variables
let a = 1; let b = 2; [a, b] = [b, a]; console.log(a, b)
The return value of the destructor function is an array
function jxy() { return [6,7,8] }; let [a,b,c]=jxy(); console.log(a,b,c); //6 7 8
The return value of the destructor function is an object
function jxy() { return {a:'jxy',b:'666'} }; let {a,b}=jxy(); console.log(a + b); //jxy666
Applying destructuring assignments to function parameters
// parameter is an array of values function f([a, b, c]) { console. log(a, b, c) } f([1, 2, 3]); // The parameter is an array of values in the form of an object function f({a, b, c}) { console. log(a, b, c) } f({a:'1', b:'5', c:'7'});
Extract certain attribute values from json data
let jxyData = { a: 'jxy', b: "18 years old", c: "cheerful" }; let {a,c,b}=jxyData; console.log(c, a, b);//cheerful jxy 18 years old
Deconstruct the default value of function parameters, specify the default value of function parameters, and avoid further judgment in the function body
function move({a = 0,b = 1} = {a:2,b:3}) { console. log(a, b); } move({a: 3,b: 4}); // 3 4 move({a: 3}); //3 1 move({b: 4}); //0 4 move({}); // 0 1 move(); // 2 3
When the map data structure is traversing the value, it can deconstruct and assign the value of each traversal
const map = new Map(); map.set('I am', 'jxy'); map.set('jxy', '666'); for (let [key, value] of map) { console.log(key + value); } // I am jxy // jxy666
When importing a module, you can specify certain methods in the imported module
const { SourceMapConsumer, SourceNode } = require("source-map");