Summary of 7 major uses of variable destructuring assignment

1: Exchange the values ​​of two variables

 let a = 12;
 let b = 32;
 [a,b] = [b,a];
 console.log(a,b)

Before ES6, when we exchange the values ​​of two variables, we often need to declare an intermediate variable. In ES6, it can be achieved by destructuring assignment. This way of writing: concise, easy to read, and clear in semantics

2: Function returns multiple values

Return an array:

function exampleArr() {
    
    
    return [1,2,3];
}
var [a,b,c] = exampleArr();
console.log([a,b,c]);

Return an object:

function exampleObj() {
    
    
    return {
    
    
        foo : 1,
        bar : 2,
        baz : 3
    }
}
var {
    
    foo ,bar ,baz} = exampleObj();
console.log(foo,bar,baz);

Essentially, a function can only return one value, but it can be placed in an array or object to return multiple values

3: Definition of function parameters:

Ordered parameters:

function f([x,y,z]){
    
    
    console.log([x,y,z])
}
f([1,2,3]);

Unordered parameters:

function f({
    
    x,y,z}){
    
    
    console.log({
    
    x,z,y})
}
f({
    
    z:3,x:22,y:31});

The principle is that destructuring assignment can associate a set of parameters with variable names

4: Extract JSON data

 var jsonData = {
    
    
     id:404,
     name:"tianqin",
     data : [13134,15331],
     status :'OK'
 }
 let {
    
    id, status, data:number, name} = jsonData
console.log(id,status,number,name);

5: Specify the default value of the function parameter

function foo({
    
    x, y = 5}) {
    
    
    console.log(x, y);
  }
  
  foo({
    
    }) // undefined 5
  foo({
    
    x: 1}) // 1 5
  foo({
    
    x: 1, y: 2}) // 1 2
  foo() // TypeError: Cannot read property 'x' of undefined

6: Traverse the Map deconstruction

 var map = new Map();
  map.set('first' ,'hello');
  map.set('second' ,'world');
  for(let [key,value] of map){
    
    
      console.log(key + "is" + value);
  }

It is very convenient to get the key name and key value

7: Specifying method of input module

const {
    
    first,second} = require('xxx');

When loading the module, you need to specify the input methods, and destructuring assignment can make the input sentence very clear

references:

[1] Ruan Yifeng. "Introduction to ES6 Standard (Second Edition)" [M]. Beijing. Publishing House of Electronics Industry. 2015:26-28

Guess you like

Origin blog.csdn.net/qq_43377853/article/details/109483821