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

Use of js array filter() method

 Arrays are frequently used in development, and processing data in arrays is one of the more common and important operations. Therefore, processing data in arrays during development is an important skill. Every developer Everyone should master the operations of arrays, especially for junior developers who have just entered the industry, so be sure to master the relevant skills. This article mainly shares some operations to filter the data in the array, about the use of the filter() method.

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.