Abstract: Fun ES6 deconstruction assignment.
- Original: 5 JS interesting use of deconstruction
- Translator: Front Ash
1. exchange variables
The method usually requires an exchange of two variables additional temporary variables to look at an example:
let a = 1;
let b = 2;
let temp;
temp = a;
a = b;
b = temp;
a; // => 2
b; // => 1
temp
Is a temporary variable, it first save a
value. Then b
the value is assigned to a
, and then the temp
value is assigned b
.
If you use a deconstructed way will be more simple, what the hell do not need temp
variable.
let a = 1;
let b = 2;
[a, b] = [b, a];
a; // => 2
b; // => 1
[a,b] = [b,a]
Deconstruction assignment, right, create an array [b, a]
, that is [2,1]
. This array 2
is assigned a given a
, is assigned to the 1 b
.
Although this approach also creates a temporary array, but at least this way to look cleaner, you can also use deconstruction exchange 2
more than one variable.
let zero = 2;
let one = 1;
let two = 0;
[zero, one, two] = [two, one, zero];
zero; // => 0
one; // => 1
two; // => 2
2. Access the elements of the array
Kind of scenario, we may have an empty item in the array. And you want to access a first array, second or n-th item, but if the entry does not exist, a default value is specified.
Typically using an array of length
property to determine
const colors = [];
let firstColor = 'white';
if (colors.length > 0) {
firstColor = colors[0];
}
firstColor; // => 'white'
Using arrays deconstruction can be more simple to achieve the same effect:
const colors = [];
const [firstColor = 'white'] = colors;
firstColor; // => 'white'
const [firstColor = 'white'] = colors
Deconstructing the colors
first element of the array is assigned to firstColor
the variable. If the array index 0
no elements at the assigned " white
" default.
Of course, it can also be more flexible, if you only want to access the second element, you can do so.
const colors = [];
const [, secondColor = 'black'] = colors;
secondColor; // => 'black'
Note the comma on the left side of deconstruction: it means to ignore the first element, secondColor
using colors
an array index 1
assignment elements.
3. Operation immutable
When I started using React
and Redux
when, forced to write some code to comply with immutability. Although at first some difficulties, but then I saw it benefits: easier to handle unidirectional data flow.
Invariance requirements can not change the original object. Fortunately, deconstruction can be changed in a manner not easily achieve certain operations.
const numbers = [1, 2, 3];
const [, ...fooNumbers] = numbers;
fooNumbers; // => [2, 3]
numbers; // => [1, 2, 3]
Deconstruction [, ... fooNumbers] = numbers
create a new array fooNumbers
, fooNumbers
containing numbers
elements in addition to the first element.
numbers
The array does not change, keep the operation invariance.
In the same manner immutable object can be deleted from the properties, from the object and then try to big
remove the foo
properties:
const big = {
foo: 'value Foo',
bar: 'value Bar'
};
const { foo, ...small } = big;
small; // => { bar: 'value Bar' }
big; // => { foo: 'value Foo', bar: 'value Bar' }
4. deconstruction iterables
In the first few cases, the use of an array of deconstruction, but it can achieve any may iterate Protocol (iterable protocol) deconstruction object.
Many native primitive types and objects are iterable: array
, string
, typed arrays
, set
and map
.
If you do not want to be limited to basic types, can be achieved through an iterative protocol can be customized deconstruction logic.
movies
It contains a movie
list of objects. Deconstruction movies
, it will title
obtain is great as a character string. Let's implement a custom iterator.
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
By defining the object Symbol.iterator
to achieve agreement iterative method is iterating title
.
Follow iterable protocol allows the movies
object into title
the specific method is to read the first movies
of title
: const [firstMovieTitle] = movies
.
The dynamic properties deconstruction
According to experience, deconstruction is more common than the deconstruction of an array of objects through the property.
Deconstruction of the object looks more simple:
const movie = { title: 'Heat' };
const { title } = movie;
title; // => 'Heat'
const {title} = movie
Create a variable title
, property and movie.title
assign it value.
When the object is to deconstruct, I was a little surprised that we still do not have to know the name of a property can use the dynamic attribute names to deconstruct objects.
In order to understand the dynamics of how the work of deconstruction, write a greet
function:
function greet(obj, nameProp) {
const { [nameProp]: name = 'Unknown' } = obj;
return `Hello, ${name}!`;
}
greet({ name: 'Batman' }, 'name'); // => 'Hello, Batman!'
greet({ }, 'name'); // => 'Hello, Unknown!'
Use 2
a parameter called greet()
function: object and attribute names.
In greet()
the interior, destructuring assignment const {[nameProp]:name ='Unknown'} = obj
using square brackets in the form of [nameProp]
reading a dynamic attribute name, name
variable receives the dynamic attribute values.
Better yet, if the property does not exist, you can specify a default value of " Unknown
."
After the code is deployed may exist BUG can not know in real time, and afterwards in order to solve these BUG, we spent a lot of time debugging log, here the way for everyone to recommend a nice BUG monitoring tools Fundebug .
Original: https://dmitripavlutin.com/5-interesting-uses-javascript-destructuring/
About Fundebug
Fundebug focus on JavaScript, applets micro-channel, micro-channel games, Alipay small program, React Native, Node.js and Java applications in real-time online monitoring BUG. Since 2016, two-eleven formally launched, Fundebug handled a total of 2 billion + error event, paying customers have Sunshine Insurance, walnut programming, lychee FM, head of the 1-to-1, micro pulse, the Youth League and many other community brands. Welcome to Free Trial !