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

Vue implements user login switching

This article example shares the specific code of ...

Summary of 6 Linux log viewing methods

As a backend programmer, you deal with Linux in m...

A Brief Analysis on the Time Carrying Problem of MySQL

The default time type (datetime and timestamp) in...

VMware virtual machine to establish HTTP service steps analysis

1. Use xshell to connect to the virtual machine, ...

Detailed explanation of slave_exec_mode parameter in MySQL

Today I accidentally saw the parameter slave_exec...

Java example code to generate random characters

Sample code: import java.util.Random; import java...

Hide div in HTML Hide table TABLE or DIV content css style

I solved a problem tonight that has been botherin...

Detailed explanation of MySql installation and login

Check if MySQL is already installed in Linux sudo...

Build Maven projects faster in Docker

Table of contents I. Overview 2. Conventional mul...

VMware Workstation 14 Pro installation and activation graphic tutorial

This article shares the installation and activati...

JavaScript timer to achieve seamless scrolling of pictures

This article shares the specific code of JavaScri...