JavaScript destructuring
Split the data structure into separate assignments
-
The destructuring body is an array or an object.
-
The destructuring source must have the Iterator interface or be transformed to have the Iterator interface.
-
Array destructuring is destructuring in order (ordered), and objects are structured by method name or property name (unordered).
-
Array destructuring destructuring sources are converted to arrays, and object destructuring destructuring sources are converted to objects.
-
When destructuring an object, keyword destructuring will continue to access the prototype chain from the current instance until it returns undefined.
grammar
The format of destructuring assignment is the syntax of destructuring assignment on the left side of =, and the initializer on the right side of =, that is, an object or an array.
Array destructuring assignment
Array destructuring assignment is based on array position, for example:
let [a,b] = [1,2] // 结果a等于1,b等于2
It is also possible to change the value of a variable through destructuring. for example:
let a = 1, b = 2;
[a,b] = [100, 200];
When the left side of = does not exactly match the right side, the variable that fails to match will be assigned the value of undefined, for example:
let [a,b,c] = [1,2] //a为1,b为2,c为undefined
So you can prevent this from happening by assigning default values to some variables. for example:
let [a,b,c=3] = [1,2] //a==1, b==2, c==3
Note: The default value will only be used if the corresponding value is not found on the right or if the value is undefined.
Sometimes, in destructuring assignment, you may only care about a part of the data, then you can assign only certain values through placeholders. for example:
let [a,,,b,,] = [1,2,3,4,5,6,7,8] //a==1 b==4
In destructuring assignment, by adding a ... sign before the variable, it indicates that the generated variable is an array. for example:
let [a,,...b] = [1,2,3,4,5] //a == 1, b==[3,4,5]
The situations shown above can be used in combination, for example:
let [a,b=8,,..c] = [1,2,3,4,5,6] //a==1 b==2 c=[4,5,6]
Object destructuring assignment
Destructuring assignment of objects is property-based. for example:
let {name, age} = {
name: 'icode007',
age: 27
}
//name == 'icode007' age==27
Like the destructuring assignment of an array, the destructuring assignment of an object assigns undefined to a variable that cannot be destructed, and the default value can also be used.
When destructuring assignments to existing variables, pay attention to adding ()
let name, age;
({name, age} = {name: 'icode007', age: 27});
This is because if () is not added, js will regard the left side as a code block, and an error will be reported. After adding (), the whole becomes a legal expression.
In the above destructuring assignment, the variable name and the property name in the object must be the same. Only in this way can the corresponding data to be destructurized and assigned can be found. But what if we want to give the data a different name? There is also a way.
let {name:myName, age: myAge} = {name: 'icode007', age: 27}
In this way, the corresponding name and age are assigned to myName and myAge.
You can also use the default values at the same time:
let {name:myName, age: myAge, jog: myJob = 'soft Engineer'} = {name: 'icode007', age: 27}
The examples of destructuring assignment of objects listed above are very simple, but in actual development, JSON data may be very complex, and the destructuring assignment syntax may also become complicated. for example:
let node = {
type: "Identifier",
name: "foo",
loc: {
start: {
line: 1,
column: 1
},
end: {
line: 1,
column: 4
}
}
};
let {loc: { start }} = node;
console.log(start.line);
console.log(start.column);
Note: Whenever : appears in destructuring assignment, the identifier on the left of : indicates the position to be checked, the right side indicates the target to be assigned, and if the right side is {} or [], it indicates that the variable to be assigned is in a deeper structure middle.
All instances of the above, such as default values, variable renaming, etc. properties may exist in a destructuring assignment statement. Moreover, the destructuring assignment of the array and the destructuring assignment of the object can also be mixed. This provides great convenience for us to extract corresponding data from complex data structures.
Destructuring of function parameters
Function parameter destructuring is useful for implementing multi-argument functions. for example
function setCookie(name, value, options){
options = options || {};
var secure = option.secure,
path = option.path,
domain = option.domain
;
//...
}
setCookie('type', 'js', {
secure: true,
expires: 60000
})
The above function is a common way to implement multi-parameter functions. Name and value are required parameters. All optional parameters are encapsulated into options and used as attributes of options. But a problem with the above function is that you can't know what the name of the optional parameter is just by looking at the definition of the function? You need to read the function code to understand the function to use it.
Destructuring with function parameters is much more intuitive:
function setCookie(name, value, {secure, path, domain}){
//...
}
This function can be called using the same usage.
But there is a problem with this way of writing that when only the name and value parameters are passed in, an error will be reported.
A better way to write it is to use the default parameters of the function.
function setCookie(name, value, {secure, path = "/", domain} = {}){
//...
}
Precautions
- In the destructuring assignment of an array, the variable using ...rest must be placed at the end.
- Like the normal variable assignment statement, the destructuring assignment statement also has a value, and its value is the content on the right side of the =.
Best Practices
Before es6, to exchange the values of two variables, you need to create an intermediate variable, like this
var a = 1, b = 2, temp;
temp = a; a = b; b = temp;
Now only one line of code is needed:[a,b] = [b,a]
In actual development, data destructuring is very complicated. The syntax of using object properties to call layer by layer is very unintuitive. By destructuring assignment, the code can be made more intuitive and concise.
There is a little trick in the destructuring assignment of an array.
let arr = [1,4,9,55,244];
let [...cloneArray] = arr;
console.log(cloneArray);
In this way, the shallow copy of the array is realized, and in the past, the copy of the array was done by the concat() method.
ES6 destructuring is not a new feature, but a new assignment syntax that lets you quickly unpack object properties and values in arrays and assign them to individual variables.
var profile = {name:'George', age:39,
hobby:'Tennis'}
var {name, hobby} = profile
Here I use destructuring to quickly extract the sum properties of profile
objects .name
hobby
Using aliases, you can use a different variable name than the object property you're extracting the value from:
var profile = {name:'George', age:39,
hobby:'Tennis'}
var {name:n, hobby:h} = profile
Nested object destructuring
Destructuring also works with nested objects, I've been using it to quickly unwrap values from complex JSON requests:
var jsondata = {
title: 'Top 5 JavaScript ES6 Features',
Details: {
date: {
created: '2017/09/19',
modified: '2017/09/20',
},
Category: 'JavaScript',
},
url: '/top-5-es6-features/'
};
var {title, Details: {date: {created, modified}}} = jsondata
console.log(title, created, modified)
destructuring array
Array destructuring works similarly to objects, except the left curly brace is replaced with square brackets:
var soccerteam = ['George', 'Dennis', 'Sandy']
var [a, b] = soccerteam
console.log(a, b) //George Dennis
You can skip certain array elements by using commas (,):
var soccerteam = ['George', 'Dennis', 'Sandy']
var [a, , b] = soccerteam
console.log(a, b) //George Sandy
For me, destructuring removes all the friction of extracting and assigning object properties and array values the traditional way. To fully grasp the complexities and potential of ES6 destructuring, read "Getting to Grips with ES6: Destructuring".
Default and Rest Parameters
Finally, the two features of ES6 that I want to bring up the most are handling function parameters. Almost every function we create in JavaScript accepts user data, so these two features come in handy more than once a month.
Default Parameters
We've all used the following pattern to create parameters with default values:
function getarea(w,h){ var w = w || 10
var h = h || 15
return w * h
}
With ES6 support for default parameters, the days of explicitly defined parameter values are over:
function getarea(w = 10, h = 15) { return w * h } getarea(5) // returns 75
Rest Parameters
Rest Parameters in ES6 makes it easy to convert function parameters into arrays.
function addit(...theNumbers) { // get the sum of the array elements return theNumbers.reduce ((prevnum, curnum) => prevnum + curnum, 0) } addit(1, 2, 3, 4) // returns 10
By adding 3 dots before the named parameter ...
, the parameters entered into the function at that position and after are automatically converted to arrays.
Without Rest Parameters, we have to do complicated operations like manually converting parameters to arrays:
function addit(theNumbers) {
var numArray =
Array.prototype.slice.call(arguments)
return numArray.reduce((prevnum, curnum) =>
prevnum + curnum, 0)
}
addit(1, 2, 3, 4)
// returns 10
Rest parameters can only be applied to a subset of the function's parameters, like the following, it will only convert the parameters to an array starting from the second:
function f1(date, ...lucknumbers) {
return 'The Lucky Numbers for ' + date +
' are: ' + lucknumbers.join(', ')
}
console.log(f1('2017/09/29', 3, 32, 43, 52));
//The Lucky Numbers for 2017/09/29 are: 3, 32, 43, 52
some small applications
1. Swapping variables is a cool way to play
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b) // 2 1
2. Accept multiple values returned by a function
function fun() {
return [1, 2, 3]
}
let [x, y, z] = fun()
console.log(x, y, z) // 1 2 3
function fun() {
return {
a: 1,
b: 2,
c: 3
}
}
let {a, b, c} = fun()
console.log(a, b, c) // 1 2 3
3. Accept function arguments out of order
function login({pwd, uid}) {
console.log(uid, pwd)
}
login({uid: '123', pwd: '456'}) //123 456
login({pwd: '456', uid: '123',}) //123 456
4. Set the default value
function login({pwd, uid, age = 18}) {
console.log(uid, pwd, age)
}
login({uid: '123', pwd: '456', age: 22}) //123 456 22
login({pwd: '456', uid: '123',}) //123 456 18
5. Provide an elegant module introduction method for modular programming
import {host} from './config'
6. The parameter list of the function can be automatically loaded into an array
function fun(head, ...others) {
console.log(head) //1
console.log(others) //[ 2, 3, 4 ]
}
fun(1, 2, 3, 4)
7. Delete an attribute of an object
let user = {
uid: "root",
pwd: 'pwd',
name: 'ahao'
}
let {name, ...new_user} = user
console.log(name) //ahao
console.log(new_user) //{ uid: 'root', pwd: 'pwd' }
8. Merge objects (shallow assignment)
let obj1 = {
name: 'a',
age: 2,
}
let obj2 = {
name: 'b',
tel: 123
}
let newObj = {...obj1, ...obj2}
console.log(newObj) //{ name: 'b', age: 2, tel: 123 }