Deconstruction assignment
The purpose of deconstruction is to get elements or attributes of an array or object quickly without using traditional methods of assignment such as ARR [x] or OBJ [key]
String deconstruction
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;
a //"h"
b //"e"
c //"l"
d //"l"
e //"o"
Copy the code
Array-like objects have a Length object, so you can also deconstruct and assign to this object
let {length:len} = "hello";
len //5
Copy the code
Destruct assignment of variables
use
(1) Exchange the values of variables
let x = 1;
let y = 2;
[x,y] = [y,x];
console.log(x,y) //x=2,y=1;
Copy the code
This writing method is not only concise, but also very semantic.
(2) Return multiple values from the function
Functions can only return one value. If you want to return multiple values, you can only return them in arrays or objects. With deconstructed assignment, it is very convenient to retrieve these values
// Return an array funlctionexample() {return} [1, 2, 3]let[a.b,c] = example ()Copy the code
(3) Definition of function parameters
Destructuring assignments makes it easy to match a set of parameters to variable names
// Arguments are an ordered set of valuesfunctionf([x,y,z]){ ... } f([1,2,3]) // arguments are an unordered set of valuesfunction f({x,y,z}){
...
}
f({Z:3,y:2,X:1})
Copy the code
(4) Extract JSON data
Deconstructing assignments is especially useful for extracting data from JSON
let jsonData ={
id :42,
status:"Ok", data: [874125]}let{id, the status, data: number0} = jsonData;Copy the code
(5) Default values of function parameters
JQuery.ajax = function(url,{
async = true ,
before = funkction(){},
cache = true{}})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” such statements
(6) Traverse the Map structure
For.. can be used for any object with the Iterator interface deployed. Of loop traversal, Map structure native support Iterator interface, with variable deconstruction assignment, obtain key names and key values is very convenient
let map = new Map();
map.set('first'.'hello');
map.set('second'.'world');
for ( let [key,value] of map){
console.log(key,value)
}
Copy the code
If you just want to get the key value or the key name, you can write it like this
// Get the key namefor( let[key] of map){} // Get the keyfor(let [,value] of map){
}
Copy the code
(7) The specified method of input module
When loading a module, you often need to specify which methods to input, and destructing assignment makes the input statements very clear
Import {Title, Link} from 'antd'Copy the code