The use of variable deconstruction assignment in JavaScript

Time:2021-6-13

introduction

Deconstruction assignment is a fast and convenient variable assignment method introduced in ES6, which is mainly divided into deconstruction and assignment. The destructor, that is, matches the structure, and then decomposes the structure for assignment.

Deconstruction assignment of arrays

use

const arr = [1,3,5]
const [a,b,c] = arr;
console.log(a) // 1
console.log(b) // 3
//Equivalent to
const a = arr[0]
const b = arr[1]

//Partial structure matching can also be deconstructed. If deconstruction is not successful, it will be undefined
const [a] = arr; //  A is 1
const [a,b,c] = arr; //  C is undefined
const [,y] = arr; //  Y is 3

//You can use patterns like rest parameters
const [a,...arrs] = arr;
console.log(arrs) // [3,5]

Specify the default value when deconstructing,The default value is valid when the position (= = =) is strictly equal to undefined

const [a,b,x,y=66] = arr; // The default value of Y is 66

Note: if the object deconstructed with [] is a non array data structure without iterator interface, an error will be reported.

Structure assignment of object

use

const person = {
  name:'zhangsan',
  age:18,
  lover:{
    name:'lishi',
    age:20
  }
}
const {name,age,lover} = person;
console.log(name); //zhangsan
console.log(lover); //{"name":"lishi","age":20}
//Equivalent to
const name = person.name;
const age = person.age;

//If the object property names cannot match, the structure fails undefined
const {age0} = person; //  Age0 is undefined

//Available: similar to alias, you can get the value of the corresponding attribute through the alias
//In this case, age 0 is 18 and age is undefined
const {age:age0} = person;

//It can also be nested and deconstructed
//When deconstructing, there should not be two identical variable names, which is quite repeated declaration
//Lovername is Lishi
const {name,lover:{name:loverName}} = person;

essence

const {age} = {age:12}
equivalence
const {age:age} = {age:12}

image
Specify the default value,The default value is valid when the position (= = =) is strictly equal to undefined

const {name='li',age=12} = {age:19}

Structure assignment of string

const [a,b,c,d] = 'haha';
const {length} = 'haha'; //  The length is 4

Deconstruction and assignment of function parameters

use

//In use, the corresponding type is deconstructed, and then it can be used as a parameter
function foo([a,b]) {return a+b}
Let result = foo ([1,3]) // result is 4
let arr = [[2,1],[2,2]].map(([a,b]) => a+b) //arr [3,4]