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
Post a Comment