The principle and application of ES6 deconstruction assignment

The principle and application of ES6 deconstruction assignment

Array destructuring assignment

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

Define multiple variables at the same time, a matches 1, b matches 2, c matches 3

Destructuring assignment allows you to specify default values. That is, if the variable on the left specifies a default value and there is no corresponding value on the right, the default value will be output first.

let [x, y = 'b'] = ['a'] // x = 'a', y = 'b'

x matches character a, and the default value of y is character b. If there is no corresponding character on the right, the default output is character b.

Destructuring assignment of objects

Deconstruction can be used not only for arrays, but also for objects. There is an important difference between object deconstruction and array deconstruction. The elements of an array are arranged in order, and the value of a variable is determined by its position; while the properties of an object have no order, and the variable must have the same name as the property to get the correct value.

let {
    name,
    age,
    hobbies: [one, two]
} = {
    name: 'shiramashiro',
    age: 21,
    hobbies: ['cycling', 'animation']
}

For example, if I change the value of age to the value of abc, since it does not correspond to the property name in the object, it cannot be assigned a corresponding value, so it is undefined.

Application of destructuring assignment

Swapping the values ​​of variables

The normal way to think of exchanging the values ​​of variables

let x = 1,
    y = 2,
    temp = 0

temp = x // x = 1 = temp
x = y // y = 2 = x
y = temp // temp = 1 = y

console.log('x => ', x)
console.log('y => ', y)

Swapping variables using destructuring assignment

let x = 1;
let y = 2;
[x, y] = [y, x];

console.log('x => ', x)
console.log('y => ', y) 

This way of exchanging the values ​​of variables x and y is not only concise but also easy to read and has very clear semantics.

Returning multiple values ​​from a function

A function can only return one value. If you want to return multiple values, you can only return them in an array or object. With destructuring assignment, it becomes more convenient.

Extract the second value in the hobbies array

function getArray() {
    return {
        name: 'kongsam',
        age: 21,
        hobbies: ['cycling', 'animation', 'badminton']
    }
}
console.log(getArray().name + 'like' + getArray().hobbies[1]) // Anime

Use destructuring assignment to get the second value in the hobbies array

let {name, age, hobbies} = getArray()
console.log(name + 'like' + hobbies[1]) // anime

Traversing the Map structure

For the for...of loop traversal, the traversed value is an array, and the deconstruction assignment can be "pattern matched" for the array, which can quickly extract the key-value.

It is very convenient to use for...of loop traversal with destructuring assignment to obtain key-value.

for (let [key, value] of map) {
    console.log("key => ", key)
    console.log("value => ", value)
}

Destructuring assignment of function parameters

// let { x = 10, y = 5 } = {}

function f({ x = 10, y = 5 } = {}) {
    return [x, y]
}

console.log(f({ x: 100, y: 50 })) // [100, 50]
console.log(f({ x: 3 })) // [3, 5]
console.log(f({})) // [10, 5]
console.log(f()) // [10, 5]

You can pass objects into the function parameters and set default values ​​for the passed objects. It will be deconstructed into the function for use, and you can understand it this way.

function f(x = 10, y = 5) {
    return [x, y]
}

console.log(f(100, 50)) // [100, 50]
console.log(f(3)) // [3, 5]
console.log(f()) // [10, 5]

Different writing methods will lead to different results.

function f({ x, y } = { x: 10, y: 5 }) {
    return [x, y]
}

console.log(f({ x: 100, y: 50 })) // [100, 50]
console.log(f({ x: 3 })) // [3, undefined]
console.log(f({})) // [undefined, undefined]
console.log(f()) // [10, 5]

The third and fourth prints will have undefined because the passed in x or y does not correspond to the value in the object property and the match fails.

The above is the detailed content of the principle and application of ES6 destructuring assignment. For more information about ES6 destructuring assignment, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of JS ES6 variable destructuring assignment
  • The difference between let and const in ES6 and the example analysis of variable deconstruction assignment operation method
  • Detailed explanation of destructuring assignment of ES6 arrays and objects
  • Detailed explanation of destructuring assignment in ES6 export default and import statements
  • Detailed explanation of ES6 destructuring assignment examples
  • ES6 knowledge points summary: object destructuring assignment application example
  • ES6 introductory tutorial: detailed explanation of variable destructuring assignment
  • ES6 basics of destructuring assignment
  • Introduction to new functions and destructuring assignment of ES6 objects
  • Analysis of the functions and usage examples of ES6 destructuring assignment
  • Detailed explanation of ES6 destructuring assignment example

<<:  Detailed explanation of the performance monitoring ideas of specified processes in Linux system based on Python

>>:  MySQL insert json problem

Recommend

js regular expression lookahead and lookbehind and non-capturing grouping

Table of contents Combining lookahead and lookbeh...

How to install MySQL and MariaDB in Docker

Relationship between MySQL and MariaDB MariaDB da...

Detailed explanation of keepAlive use cases in Vue

In development, it is often necessary to cache th...

Solving problems encountered when importing and exporting Mysql

background Since I converted all my tasks to Dock...

jQuery implements navigation bar effect with expansion animation

I designed and customized a navigation bar with a...

How to manually upgrade the kernel in deepin linux

deepin and Ubuntu are both distributions based on...

Implementation of MySQL scheduled backup script under Windows

On a Windows server, if you want to back up datab...

Detailed examples of Zabbix remote command execution

Table of contents one. environment two. Precautio...

A brief discussion on the pitfalls of react useEffect closure

Problem code Look at a closure problem code cause...

How to safely shut down MySQL

When shutting down the MySQL server, various prob...

How to use React to implement image recognition app

Let me show you the effect picture first. Persona...

Implementation of mounting NFS shared directory in Docker container

Previously, https://www.jb51.net/article/205922.h...

A brief discussion on the lazy loading attribute pattern in JavaScript

Table of contents 1. Introduction 2. On-demand at...