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

A simple understanding of ES6 iterators

 What is an iterator?An iterator is an interface that provides a unified access mechanism for various data structures. Any data structure can complete the traversal operation as long as the iterator interface is deployed.ES6 created a new traversal command for...of loop, which natively has a data structure with the iterator interface (which can be traversed with for...of). Contains Array, Arguments, Set, Map, String, TypedArray, NodeList. Of course, you can also implement this interface manually, which is convenient for practical use.