Skip to main content

Destructuring assignment in ES6

 In the past, when we wanted to assign a value to a variable, such as an array type and an object type, to assign a value to a variable, we could only specify the value directly. It is very troublesome to write in this way, but under the ES6 syntax specification, it is allowed to directly extract the required values from arrays and objects according to a certain pattern, and directly assign variables to variables. This method is called Destructuring, which is simple to understand. That is, the left and right sides of the equal sign are equal.

Basic usage: arrays

let [a, b, c] = [0, 1, 2];
//a=0,b=1,c=2
let [, a, b] = [0, 1, 2]
//a=1,b=2
let [x,y,...z]=[10,20,30,40,50]
//x=10,y=20,z=[30,40,50]

Basic Usage: Objects

The variable must have the same name as the property to get the correct value.

let { id, name } = { id: 'aaa', name: 'bbb' };
let{m, n = 5,c} = {m: 1};
//m=1,n=5,c=undefined
 let obj={a:10,b:"bbb"}
let {a,b}=obj
 console.log(a,b)//10 "bbb"

Comments

Popular posts from this blog

vue routing global guard beforeEach and afterEach

 Global routing front guard (beforeEach) This function is used the most. Its function is to perform permission-related verification before routing jumps. This function contains three parameters: to: the object of the target route that is about to enter; from: the route that the current route is leaving; next: confirm the release. It can be used to log in and register, to determine whether there is a token before logging in, and release if it exists. , if it does not exist, it will not be released. The post routing guard (afterEach), its role is to trigger after the routing jump.

ES6 arrow functions

 In ES6, in addition to the new features of let and const, arrow functions are the most frequently used new features. But this feature is not unique to ES6. Arrow functions, as the name suggests, are functions defined using arrows (=>) and belong to a class of anonymous functions. It allows us to write smaller function syntaxes. The code of arrow functions is simpler and more flexible to write.