1. Use
Definition: ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern called deconstructed assignment
- Swap the values of variables
let x = 1;
let y = 2;
[x, y] = [y, x];
Copy the code
- Returns multiple values from a function
A function can return only 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.
// 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()
Copy the code
- Definition of function parameters
Destructuring assignments makes it easy to map a set of parameters to variable names
// Arguments are an ordered set of values
function f([x, y, z]) {}
f([1.2.3])
// Arguments are an unordered set of values
function f({x, y, z}) {}
f({z: 3.y: 2.x: 1})
Copy the code
- Extracting JSON data
Deconstructing assignment is particularly useful for extracting data from JSON objects, which can quickly extract the value of JSON data.
let jsonData = {
id: 42.status: 'ok'.data: [90.89]};let{id, status, data, number} = jsonData;console.log(id, status, number);
Copy the code
- Specify default values
let [foo = true] = [];
foo;
let [x, y = 'b'] = ['a']; // x = a; y = b;
let [x, y = 'b'] = ['a'.undefined]; // x = 'a'; y ='b'
Copy the code
let [x = 1] = [undefined]; // x = 1;
let [x = 1] = [null]; // x = null
Copy the code
Because ES6 uses the strict equality operator (===) internally to determine whether a position has a value, the default is only valid if an array member is strictly equal to undefined.
If the default value is an expression, the expression is lazy and evaluated only when it is used
function f() {
console.log('aaa');
}
let [x = f()] = [1];
Copy the code
The above function does not execute at all. The above code is equivalent to:
let x;
if([1] [0= = =undefined) {
x = f();
} else {
x = [1] [0]}Copy the code
The default value can refer to another variable of the deconstructed assignment, but that variable must already be declared.
let [x = 1, y = x] = []; // x=1; y=1
let [x = 1, y = x] = [2]; // x=2; y=2
let [x = 1, y = x] = [1.2]; // x=1; y=2
let [x = y, y = 1] = []; // ReferenceError: y is not defined
Copy the code
- Traverse Map deconstruction
const map = new Map(a); 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.
// Get the key name
for(let [key] of map) {
}
// Get the key value
for(let [,value] of map) {
}
Copy the code
- The specified way to write an input module
const { SourceMap } = require('source-map')
Copy the code
2. Basic usage
let a = 1;
let b = 2;
let
Copy the code