Deconstruction assignment
The destruct assignment syntax is a Javascript expression. By deconstructing assignments, attributes/values can be taken from objects/arrays and assigned to other variables.
Object to deconstruct
In ES5, we might have to write a lot of repetitive code to get specific data from objects or arrays into local variables. As follows:
const person = {
name: "zzzhim".age: 23.sex: "Male"
}
// Get the specified data in the object
const name = person.name
const age = person.age
const sex = person.sex
/ /...
Copy the code
As you can see from the above code, if we want to retrieve the specified data in the object, we must assign each value individually. Although this seems simple, it can become cumbersome if we need to extract a lot of data. This is why destructuring assignments to objects and arrays are added in ES6.
Object deconstruction syntax uses object literals on the left side of assignment statements. As follows:
const person = {
name: "zzzhim".age: 23.sex: "Male"
}
const { name, age, sex } = person
console.log(name, age, sex) / / zzzhim 23 male
Copy the code
In the above code, the values of Person. name, person.age, and person.sex are stored in local variables of name, age, and sex, respectively.
? < div style = “box-sizing: border-box; color: RGB (50, 50, 50); line-height: 20px; font-size: 14px! Important; white-space: inherit! Important;”
We can see that we can achieve the same effect using object deconstruction assignment in ES6, but the code is much more streamlined and does not repeat operations even when dealing with large amounts of data.
! < span style = “box-sizing: border-box; color: RGB (50, 50, 50); line-height: 20px; font-size: 14px! Important; white-space: inherit! Important;”
No declarative assignment
We can do undeclared assignment as well as variable declaration destructuring assignment. As follows:
let name, age, sex
const person = {
name: "zzzhim".age: 23.sex: "Male"
}
// Use destruct assignment to assign corresponding values; ({ name, age, sex } = person)console.log(name, age, sex) / / zzzhim 23 male
Copy the code
In the above example, the variables name, age, and sex have all been declared, and then we get the corresponding property of the same name on person by deconstructing it.
! This is because {name, age, sex} on the left is considered to be a block rather than an object literal. Wrapping the code block in parentheses indicates that what is inside is not a block but should be interpreted as an expression. (…). Expressions may sometimes be preceded by a semicolon, or they may be executed as if they were the function on the previous line.
The default value
The variable can be given a default value first. When the object to be extracted has no corresponding attribute or the value is undefined, the variable will be given a default value. As follows:
const person = {
name: "zzzhim".age: 23.sex: undefined
}
const { name, age, sex = "Male", height = "1.85" } = person
console.log(name, age, sex, height) // zzzhim 23 male 1.85
Copy the code
As you can see from the above example, we declare a default value for sex and height, which will be applied if the person object does not have sex and height, or if the value of the property is undefined.
Alias: Assigning the property value of an object to a different variable name
In the previous example, we assigned the property value of the object to the same variable name. Destruct assignment in ES6 also supports assigning different variable names to the property name of the object. As follows:
const person = {
name: "zzzhim"
}
const { name: englishName } = person
console.log(englishName) // zzzhim
Copy the code
{name: englishName} = person: reads the name property on the Person object and assigns its value to the variable englishName. You can see that this syntax is the opposite of the traditional literal syntax we use, which places names to the left of colons and values to the right. In this case, the name is on the right and the value is on the left.
Add default values to the alias
We can add default values to variable aliases, again adding equal signs and default values after local variable names. As follows:
const person = {
name: "zzzhim".age: undefined
}
const { age: localAge = 23 } = person
console.log(localAge) / / 23
Copy the code
Nested object deconstruction
Using syntax similar to object literals, we can drill down into nested object structures to extract the data we want. As follows:
const person = {
name: {
englishName: 'zzzhim'.chineseName: 'Anti-celery League leader'}}const { name: { englishName, chineseName } } = person
console.log(englishName, chineseName) // Zzzhim, head of the Anti-celery coalition
Copy the code
As you can see from the above example, curly braces are used on the destruct assignment to indicate that the englishName and chineseName properties should be looked for in the Name property of the Person object.
Of course, nested object destruction also supports parameter defaults and aliases.
const person = {
name: {
chineseName: 'Anti-celery League leader'}}const { name: { englishName = "zzzhim".chineseName: localName } } = person
console.log(englishName, localName) // Zzzhim, head of the Anti-celery coalition
Copy the code
An array of deconstruction
The syntax for array deconstruction is similar to object deconstruction, except that object literals ({}) are replaced by array literals ([]). When an array is structured, the deconstruction is based on the positions inside the array, rather than the named properties on the object, as is the case with objects. As follows:
const nums = [ 1.2.3 ]
const [ one, two, three ] = nums
console.log(one) / / 1
console.log(two) / / 2
console.log(three) / / 3
Copy the code
The array deconstruction above takes 1, 2, and 3 from the NUMS array and assigns them to the one, two, and three variables. These values are assigned based on their position in the array, not on the variable name.
When we only want to extract the third numS value, we can also omit certain values in array deconstruction. As follows:
const nums = [ 1.2.3 ]
const [ , , three ] = nums
console.log(three) / / 3
Copy the code
! < span style = “box-sizing: border-box; color: RGB (51, 51, 51); line-height: 20px; font-size: 14px! Important; white-space: inherit! Important;”
We can also use array deconstruction in assignment expressions. As follows:
let one, two, three
const nums = [ 1.2.3 ]
;[ one, two, three ] = nums
console.log(one) / / 1
console.log(two) / / 2
console.log(three) / / 3
Copy the code
? The difference between array deconstruction and object structure in > assignment expressions is that the expression does not have to be enclosed in parentheses (()) in array expressions.
A useful example of array deconstruction is that you can easily swap the values of two variables. As follows:
let a = 1,
b = 2; [ a, b ] = [ b, a ]console.log(a, b) / / 2, 1
Copy the code
The default value
Array deconstruction assignments also support default values, which are applied when the array location item does not exist or the value is undefined. As follows:
const nums = [ 1.undefined ]
const [ one, two = 2, three = 3 ] = nums
console.log(one) / / 1
console.log(two) / / 2
console.log(three) / / 3
Copy the code
Nested deconstruction
The same array also supports nested deconstruction. By inserting another array pattern into the entire deconstruction pattern, the deconstruction operation will descend into the nested array. As follows:
const nums = [ 1[2.3].4 ]
const [ one, [ two, three ], four ] = nums
console.log(one) / / 1
console.log(two) / / 2
console.log(three) / / 3
console.log(four) / / 4
Copy the code
Destruct an array returned by a function
It is quite common to return an array from a function. Array destructuring also supports destructuring an array returned by a function.
function fun() {
return [ 1.2]}const [ one, two ] = fun()
console.log(one) / / 1
console.log(two) / / 2
Copy the code
The remaining items
As with the remaining parameters of a function, array deconstruction has a similar concept called rest items, which uses… Syntax to assign the remaining items to a specified variable. As follows:
const nums = [ 1.2.3 ]
const [ one, ...restNums ] = nums
console.log(one) / / 1
console.log(restNums) // [2, 3]
Copy the code
The first item of nums is assigned to the variable one, and its remaining parameters are added to restNums as an array.
In ES5 we want to clone an array, and we might use concat() to clone the array. In ES6, we can do the same thing more easily with the remaining arguments.
Clone array in ES5:
const nums = [ 1.2.3 ]
const copyNums = nums.concat()
console.log(copyNums) // [1, 2, 3]
Copy the code
Concat method: Used to merge two or more arrays. This method does not change an existing array, but returns a new array.
ES6 clone arrays with remaining parameters:
const nums = [ 1.2.3 ]
const copyNums = [ ...nums ]
console.log(copyNums) // [1, 2, 3]
Copy the code
! > The rest of the array argument must be the last part of the array destruction. no comma after it, otherwise it is a syntax error.
Deconstruct nested objects and arrays
Object and array deconstruction can be used together to create more complex deconstruction expressions.
const createElement = [
'div',
{
className: 'foo'.style: {
color: 'red'.fontSize: '14px'}},'This is a piece of content! '['h1',
{},
'It's a text! ']]]const [
,
{
className,
style: { color, fontSize }
},
content
] = createElement
console.log(className) // foo
console.log(color) // red
console.log(fontSize) // 14px
console.log(content) // ['h1', ['h1', {}, 'this is text!']]
Copy the code
This code extracts the className from the createElement[1] object in the createElement array and the values of color, fontSize, and createElement[2] under style. Using a mixture of object and array deconstruction, you can extract any part of a createElement.
Function argument deconstruction
Another scenario where deconstruction is particularly useful is when passing function arguments.
function setCookie(name, value, { secure, path, domain, expires }) {
console.log(secure) // true
console.log(path) // undefined
console.log(domain) // undefined
console.log(expires) / / 60000
// Set the cookie code
}
// The third argument maps to the third argument of setCookie
setCookie(
"type"."js",
{
secure: true.expires: 60000})Copy the code
The above code can be viewed this way.
function setCookie(name, value, options) {
let { secure, path, domain, expires } = options
console.log(secure) // true
console.log(path) // undefined
console.log(domain) // undefined
console.log(expires) / / 60000
// Set the cookie code
}
// The third argument maps to the third argument of setCookie
setCookie(
"type"."js",
{
secure: true.expires: 60000})Copy the code
However, there is a slight problem with the above code. When we call the function by default and do not pass the third argument, the destruct assignment will throw an error. As follows:
function setCookie(name, value, { secure, path, domain, expires }) {
console.log(secure) // true
console.log(path) // undefined
console.log(domain) // undefined
console.log(expires) / / 60000
// Set the cookie code
}
// Throw error Cannot destructure property 'secure' of 'undefined' or 'null'.
setCookie("type"."js")
Copy the code
This is because when the function is called, when we don’t pass the third argument, it actually defaults to undefined, causing the argument to throw an error when it is deconstructed.
To fix the above error, we can set a default value for the function argument. Our default value will be applied when the user does not pass or passes undefined. As follows:
function setCookie(
name,
value,
{
secure = true, //The default value for destructuring function arguments is path ="",
domain,
expires = 60000
} = {}
) {
console.log(secure) // true
console.log(path) / / ""
console.log(domain) // undefined
console.log(expires) / / 60000
// Set the cookie code
}
setCookie("type"."js")
Copy the code
That way there are no errors thrown.
? The default value for destructuring function arguments is specified by adding an equal sign after each argument in the example above.
conclusion
Deconstruction makes it easier to manipulate objects and arrays in JS. Using the familiar syntax of object literals and array literals, you can separate data structures and get only the information you’re interested in. Object deconstruction mode allows you to extract from objects, while array mode can be used for arrays.
Both object and array destruction can provide default values for properties or items that are not defined; Both modes throw an error when the value to the right of an assignment expression is null or undefined. You can also use object and array deconstruction in deeply nested data structures, descending to any depth in the structure.
To create a variable using a destruct declaration of var, let, or const, you must provide an initializer. Destruct assignment replaces other assignments and allows you to destruct values into object properties or existing variables.
Parameter deconstruction makes “options” objects more transparent by using the deconstruction syntax as arguments to functions. The data you are actually interested in can be listed along with the named parameters. The parameters for deconstruction can be object mode, array mode, or hybrid mode, and you can use all of their features.
6 Reading notes.
- ES6 block-level binding, let, const declaration
- Strings and Regular expressions (RegExp)
- Functions
- Extended object functionality
- Deconstruction assignment
- Symbol and Symbol attribute
Refer to the article
- MDN
- Understanding ECMAScript 6
- Understanding ECMAScript 6