Deconstruction in JS
**Statement: * * article taken from Crazy technology house Front end stack Sunny trees This article is a learning record based on the contents of predecessors.
Deconstruction and use of variables
The deconstruction of variables is mainly used to read, access and operate some attributes or values. Here are five common variable deconstruction operations.
1. Exchange variable
Usually, two variables are exchanged, and we will transfer the value with an intermediate variable. The example here is a simple original value type. If you switch to the reference value type, the idea is the same. The reason is that the variable of reference value type is an address value in the heap. The actually saved value is in the stack, and the content allocated by the system will not change. When we exchange variables, we just change the pointing position.
let a = 1; let b = 2; let temp; temp = a; a = b; b = temp; a; // => 2 b; // => 1
Deconstruction allocation makes variable exchange simple without any temporary variables:
let a = 1; let b = 2; [a, b] = [b, a]; a; // => 2 b; // => 1
Temporarily build an array on the right to store [2,1], and assign the first and second items of the array to a and B respectively. The best way to use this method for data exchange is: concise, you can exchange any number of variables as needed! As for memory recycling, js will recycle the memory of unused variables.
2. Access array items
If we want to get an element of an uncertain array or other structure type data, if it doesn't exist, we will give the variable default value. The usual practice is based on the array (structure) length to judge.
const colors = []; let firstColor = 'white'; if (colors.length > 0) { firstColor = colors[0]; } firstColor; // => 'white'
Array deconstruction does this
const colors = []; const [firstColor = 'white'] = colors; firstColor; // => 'white'
const [firstColor = 'white'] = colors deconstruction assigns the first element of the colors array to the firstColor variable. If the array does not have any elements at index 0, the default value white is assigned. You can access only the second element if you want to:
const colors = []; const [, secondColor = 'black'] = colors; secondColor; // => 'black'
Notice the comma on the left side of the structure: this means that the first element will be ignored. secondColor was assigned to the element with index 1 from the color array.
Compared with the slice() method of getting some elements in the Array in Array, we can add default values.
3. Invariant operation
Extract a subset array from the original array, and the above case is to extract an element.
const numbers = [1, 2, 3]; const [, ...fooNumbers] = numbers; fooNumbers; // => [2, 3] numbers; // => [1, 2, 3]
Deconstructing [,... Foofnumbers] = numbers will create a new array foofnumbers, which contains all elements except the first item. The numbers array does not mutate, leaving the operation unchanged.
In addition to operating the array in this way, we can also apply the structure to the object attribute,... Small deconstructs the assignment. The data type of small depends on the object to be deconstructed, that is, it is consistent with the variable type on the right of the equal sign. Object is the data type that implements the iterator protocol, so it can be iterated,... Returns each attribute in the object, and the attribute name automatically adapts to the attribute on the right, The combination is the object with the foo attribute deleted.
const big = { foo: 'value Foo', bar: 'value Bar' }; const { foo, ...small } = big; small; // => { bar: 'value Bar' } big; // => { foo: 'value Foo', bar: 'value Bar' }
It should be noted that when deleting some attributes in an object, we need to know the attribute name, which is similar to a one-to-one mapping relationship.
const big = { foo: 'value Foo', bar: 'value Bar' }; const { foo1, ...small } = big; console.log(small)//{foo: 'value Foo', bar: 'value Bar'}
4. Deconstructing iteratable objects
Earlier, we applied deconstruction to arrays. But you can deconstruct any object that implements an iterative protocol. Many native primitive types and objects are iteratable: arrays, strings, typed arrays, collections, and mappings. For example, you can decompose a string into characters:
const str = 'cheese'; const [...first] = str; const [seconde] = str; console.log(first);//['c', 'h', 'e', 'e', 's', 'e'] console.log(seconde);//c
Not limited to native types, deconstruction logic can also be defined by implementing iterative protocols.
const movies = { list: [ { title: 'Heat' }, { title: 'Interstellar' } ], [Symbol.iterator]() { let index = 0; return { next: () => { if (index < this.list.length) { const value = this.list[index++].title; return { value, done: false }; } return { done: true }; } }; } }; const [firstMovieTitle] = movies; console.log(firstMovieTitle); // => 'Heat'
Movies object by defining symbol Iterator method to implement an iterative protocol. Iterator traverses the title of the movie. Following the iterative protocol, the movies object can be structured into titles, especially by reading the title of the first movie: const [firstMovieTitle] = movies.
5. Deconstruction dynamic attribute
It is more common to deconstruct objects through attributes than arrays.
const movie = { title: 'Heat' }; const movie1={ }; const { title = "hhh" } = movie; const { title1 = "hhh" } = movie; const{title2="123"}=movie1; console.log(title);//Heat console.log(title1);//hhh console.log(title2);//123
Similar to the deconstruction of key value pairs, the corresponding value can be obtained from the object through the key. Key does not exist, take the default value as the value. If no default value is specified and there is no key property name with the same name on the right, it returns undefined. You can also use aliases:
const { identifier: aliasIdentifier } = expression;
Identifier is the name of the attribute to be accessed, alias identifier is the name of the variable, and expression should be evaluated as an object. After destruction, the variable aliasIdentifier contains the attribute value.
Equivalent code:
const aliasIdentifier = expression.identifier;
For deconstructing objects with dynamic attribute names: this dynamic is really not what we think it is. Due to the most basic limitation [keys must be the same as the attribute name in the deconstructed object before they can be deconstructed], the dynamics here can be similar to passing parameters, selectively extracting some attributes from an object and returning them.
const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const prop = 'name'; const { [prop]: name } = hero; name; // => 'Batman'
Const {[prop]: name} = hero is an object decomposition. Assign the variable to namevalue hero[prop], where prop is a variable that saves the attribute name. The following is an example of a function:
<body> <button onclick="test1({name:'Bobo'},'name')"> test</button> </body> <script> function test1(obj,nameProp){ const{[nameProp]:name}=obj; console.log(obj)//{name: 'Bobo'} console.log(`hellow ${name}`) //Hello Bobo return `hellow ${name}`; } </script>
Deconstruction of parameters
Parameter deconstruction is mainly used in methods, which means stronger compatibility.
The traditional parameter order can not be placed at will, because each position corresponds to the actual value passed in by the calling function.
function test(val1,val2){ console.log(`The first parameter is ${val1},The second parameter is ${val2}`); } //The order of arguments and formal parameters is one-to-one correspondence test(1,2); test(2,1);
What to do if you can't remember multiple parameters? At this time, you can pass the object. The advantage of the object is that you don't need to pass the parameters in the order of parameters. Compared with the parameter list, it's better to remember the object attributes, and there is no mandatory order. If the naming is clear enough, you can understand it immediately when maintaining the code in the later stage, even by looking at the attribute name.
function infomation (user) { // user.name } infomation({ name: 'xiaoer', age: 18 })
The replacement of the parameter list by the object solves the problem of the order of the parameter list, but each call needs to take values from the object, so that the function has to access the object every time, resulting in longer variable length and many meaningless assignments. In addition, if the caller accidentally passes more parameters and traverses the object in the function, a BUG may be generated, which can be solved by deconstruction assignment:
function infomation ({ name, age, height }) { console.log(name) // Potion brother console.log(age) // 18 console.log(height) // 173cm } infomation ({name: ' Potion brother ',age: ' 18 ', height: ' 173cm '})
At this time, the parameter is not optional. For parameter options that are not entered, the default value is undefined.
function test2({name,height,age}){ console.log(`${name},${height},${age}`) } test2({name:'Bobo'}) //Bobo, undefined,undefined
In order to solve the problem of default value, we can make the relationship between our arguments and formal parameters more loose, and even do not enter parameters
function infomation ({ name = 'anonymous', age = 0, height = 160 }) { console.log(name) // Potion brother console.log(age) // 0 console.log(height) // 160 } infomation ({ name: ' Potion brother '}) function move({x = 0, y = 0} = {}) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, 0] move({}); // [0, 0] move(); // [0, 0]
Function parameter rename:
Sometimes you need to rename a parameter, but this parameter has been used in many places. It can be renamed at the beginning of function execution, but this is obviously not enough geek (mainly not lazy). It still uses deconstruction assignment to rename:
function infomation ({ name:username = 'anonymous', age = 0, height = 160 } = {}) { console.log(name) // undefined console.log(age) // 0 console.log(height) // 160 console.log(username) // anonymous } infomation()