Understanding and application of JavaScript ES6 destructuring operator

Understanding and application of JavaScript ES6 destructuring operator

Preface

I have been learning JavaScript recently and saw the deconstruction symbol in ES6. I think this has brought a leap forward in the simplicity of our code, and it has been used in enterprise development. If others are using it at work in the future, but you cannot understand their code, the impact will be huge. So, study hard.

You can use it, but you can't not understand it✔

In JavaScript ES6, there are many features that are designed to simplify the code and make it easier for programmers to write. The deconstruction operator is one of the best features. It can make the code more concise and enhance the readability of the code by reducing the use of assignment statements or reducing the way to access data subscripts and object properties.

The role of deconstruction symbols

Destructuring assignment is an extension of the assignment operator. It is a method of pattern matching for arrays or objects and then assigning values ​​to the variables in them.

ES6 allows you to extract values ​​from arrays and objects and assign values ​​to variables according to a certain pattern, which is called destructuring.

How to use

Basic Use

let [a,b,c] = [1,2,3];
// let a = 1, b = 2, c = 3;

Nested use

// Array let [a, [[b], c]] = [1, [[2], 3]];
	console.log(a); // 1
	console.log(b); // 2
	console.log(c); // 3
// Object let obj = { x: ['hello', {y: 'world'}] };
 let { x: [x,{ y }] } = obj;
	console.log(x); // hello
	console.log(y); // world

neglect

// Array let [a, , b] = [1, 2, 3];
	console.log(a); // 1
	console.log(b); // 3

// Object let obj = { x: ['hello', { y: 'world' }] };
 let { x: [x, { }] } = obj;
	console.log(x); // hello

Incomplete deconstruction

// Array let [a = 1, b] = [];
	console.log(a); // 1
	console.log(b); // undefined

// Object let obj = { x: [{ y: 'world' }] };
 let { x: [{ y }, x] } = obj;
	console.log(x); // undefined
	console.log(y); // world

Rest Operator

// Array let [a, ...b] = [1, 2, 3];
	console.log(a); // 1
	console.log(b); // [2,3]

// Object let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
	console.log(a); // 10
	console.log(b); // 20
	console.log(rest); // { c: 30, d: 40 }

String

let [a, b, c, d, e] = 'hello';
console.log(a); // h
console.log(b); // e
console.log(c); // l
console.log(d); // l
console.log(e); // o

Destructuring default values

// When the deconstruction pattern has a matching result, and the matching result is undefined, the default value will be triggered as the return result.
 let [a = 2] = [undefined]; 
	console.log(a); // 2
// Object let {a = 10, b = 5} = {a: 3};
 	console.log(a); // 3
 	console.log(b); // 5

Swap the values ​​of variables.

let a = 1;
let b = 2;
[a,b] = [b,a];
	console.log(a); // 2
	console.log(b); // 1

Application of destructuring assignment

// 1. Shallow cloning and merging let name = { name: "aaa" }
let age = { age: 'bbb' }
let person = { ...name, ...age }
console.log(person) // { name: "aaa", age: 'bbb' }

let a = [1,2,3];
let b = [4,5];
let c = [...a,...b];
console.log(c); // [1,2,3,4,5]

// 2. Extract JSON data let JsonData = { id: 10, status: "OK", data: [111, 222] } 
let { id, status, data: numbers } = JsonData; 
console.log(id, status, numbers); //10 "OK" [111, 222]

// 3. Definition of function parameters // Parameters in order function fun1([a, b, c]) { console.log(a, b, c) } 
fun1([1, 2, 3]); // 1 2 3

// Parameters are out of order function fun2({ x, y, z }) { console.log(x, y, z) } 
fun2({ z: 3, x: 2, y: 1 }); // 2 1 3

// Parameters have default values ​​function fun3 ([a=1,b]) {
console.log(a,b);
}
fun3([,3]) // 1 3

Brief Talk on Application

Extract json data

Several applications of deconstruction assignment are listed above. The second one we use most often is to extract JSON data. The data passed from the back end to the front end is JSON data. The front end usually assigns the data to an object, which is the method used.

The expandable operator...

I used it when I was doing questions on Leetcode. I used arr.push(...arr1) to merge two arrays, which is a bit like the shallow cloning and merging above. Compared to our previous operations of merging arrays, this is much simpler.

Question 88, merge two sorted arrays.

var merge = function(nums1, m, nums2, n) {
    nums1.length=m;
    nums2.length=n;
    nums1.push(...nums2);
    let arr = nums1.sort((a,b)=>{
        return ab;
    })
    return arr;
};

...This operator traverses the data in the array and copies it to the current object.

The method arr.push(...arr1) will parse out all the array elements of arr1 and then add them to arr one by one, completing the merger of the two arrays.

Swapping variable values

Let’s take a look at the application of exchanging variable values. I vaguely remember an interview question from a senior: exchange the values ​​of a and b without taking up extra memory space. There were two solutions at that time. One was to use XOR, and the other was to use mathematical methods to add ab and then subtract them separately, (a=a+b, b=ab, a=ab). Now, using the method of deconstructing symbols [a,b] = [b,a], is it also possible?

Summarize

This concludes this article on the understanding and application of JavaScript ES6 destructuring operators. For more information about ES6 destructuring operators, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • 5 interesting uses of JS destructuring
  • Parsing destructuring assignments in ES6 version of JavaScript
  • An article to help you understand JavaScript destructuring assignment
  • Example analysis of the usage of JavaScript object destructuring
  • A practical guide to JavaScript destructuring assignment
  • JavaScript destructuring assignment detailed explanation
  • Javascript destructuring assignment details
  • Summary of common usage of javascript destructuring assignment under ES6

<<:  Detailed explanation of docker-machine usage

>>:  Tutorial on using hyperlink tags in XHTML

Recommend

Recommended tips for web front-end engineers

Let's first talk about the value of web front...

MySQL full-text search usage examples

Table of contents 1. Environmental Preparation 2....

MySQL 5.7.21 installation and configuration tutorial

The simple installation configuration of mysql5.7...

Docker mounts local directories and data volume container operations

1. Docker mounts the local directory Docker can s...

MySQL 8.0.15 installation tutorial for Windows 64-bit

First go to the official website to download and ...

Detailed explanation of Vue options

Table of contents 1. What are options? 2. What at...

How to implement MySQL master-slave replication based on Docker

Preface MySQL master-slave replication is the bas...

How to set a dotted border in html

Use CSS styles and HTML tag elements In order to ...

How to collect Nginx logs using Filebeat

Nginx logs can be used to analyze user address lo...

How to use CSS to pull down a small image to view a large image and information

Today I will talk about a CSS special effect of h...

How to locate MySQL slow queries

Preface I believe that everyone has had experienc...

Example of MySQL auto-increment ID exhaustion

Display Definition ID When the auto-increment ID ...

How to use the Clipboard API in JS

Table of contents 1. Document.execCommand() metho...