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

What is the difference between the box-size property content-box and border-box in the css box model?

 The box model is a very important concept in CSS layout, it includes content area, padding, border, and margin. Box models can be divided into two types: standard box models and IE box models. The box model, as the name suggests, is used to hold things, and the things it holds are the content of HTML elements. In other words, every visible HTML element is a box.

Js uses recursive way to traverse the dom tree to dynamically create element nodes

 What is a dom tree? In short, DOM is the Document Object Model, which provides a structured representation for documents and defines how to access the document structure through scripts. DOM is composed of nodes. After the HTML is loaded, the rendering engine will generate a DOM tree in memory based on the HTML document. This article uses a small case to traverse the dom tree recursively. The core of the method is to determine whether the incoming data is an array, and then traverse the root node. Note that there must be an end condition when using recursion.