Home > Web Front-end > JS Tutorial > Master the principles and applications of ES6 destructuring assignment in one article

Master the principles and applications of ES6 destructuring assignment in one article

WBOY
Release: 2022-08-08 14:03:56
forward
1706 people have browsed it

This article brings you relevant knowledge about javascript. ES6 allows you to extract values ​​from arrays or objects according to a certain pattern, and then assign values ​​to variables, which is called destructuring. As long as the patterns on both sides of the equal sign are the same, the variable on the left will be assigned the corresponding value. This writing method belongs to "pattern matching". Collectively, it is called "destructuring assignment". Let’s take a look at it together, I hope it will be helpful to everyone.

Master the principles and applications of ES6 destructuring assignment in one article

[Related recommendations: javascript video tutorial, web front-end

Destructuring and assignment of arrays

let [a, b, c] = [1, 2, 3]
Copy after login

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

Destructuring assignment allows the default value to be specified, that is, the left variable specifies the default value , if there is no corresponding value on the right, the default value will be output first.

let [x, y = 'b'] = ['a'] // x = 'a', y = 'b'
Copy after login

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

Destructuring assignment of objects

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

let {
    name,
    age,
    hobbies: [one, two]
} = {
    name: 'shiramashiro',
    age: 21,
    hobbies: ['骑行', '动漫']
}
Copy after login

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

The use of destructuring assignment

Exchanging the value of a variable

The normal way to think of exchanging the value of a variable

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)
Copy after login

Exchanging variables using destructuring assignment

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

console.log('x => ', x)
console.log('y => ', y)
Copy after login

Exchanging the values ​​of variables x and y in this way is not only concise, but also easy to read, and the semantics are very clear.

Returning multiple values ​​from the function

The function can only return one value. If you want to return multiple values, you can only return them in an array or object. There is destructuring Assignment becomes more convenient.

Extract the second value in the hobbies array

function getArray() {
    return {
        name: 'kongsam',
        age: 21,
        hobbies: ['骑行', '动漫', '羽毛球']
    }
}
console.log(getArray().name + '喜欢' + getArray().hobbies[1]) // 动漫
Copy after login

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

let {name, age, hobbies} = getArray()
console.log(name + '喜欢' + hobbies[1]) // 动漫
Copy after login

Traverse the Map structure

For...of loop traversal, the traversed value is an array, and destructuring assignment can "pattern match" the array, which can quickly remove the key-value.

#for...of loop traversal and destructuring assignment are very convenient to obtain the key-value.

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

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]
Copy after login

You can pass in objects to the parameters of the function, and you can set default values ​​for the passed in 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]
Copy after login

The above writing methods are different, which will also 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]
Copy after login

The third and fourth prints will have undefined. This is because the incoming x or y does not correspond to the object attribute. The value in is caused by unsuccessful matching.

【Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of Master the principles and applications of ES6 destructuring assignment in one article. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
es6
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template