Destruct assignment of variables
An array of
Previously, to assign a value to a variable, you could only specify a value directly:
let a = 1;
let b = 2; ,,,,,,Copy the code
But now, ES6 allows us to write this:
let [a,b] = [1.2];
//a:1;
//b:2;
Copy the code
The above code shows that you can assign values to variables at their respective positions in an array. One thing to note, though, is that the pattern on both sides of the equality sign needs to be the same. Here are some examples
let [foo, [[bar], baz]] = [1The [[2].3]];
foo / / 1
bar / / 2
baz / / 3
let [ , , third] = ["foo"."bar"."baz"];
third // "baz"
Copy the code
If the two sides of the equal sign have different modes and the structure is unsuccessful, the value of the variable is Undefined.
let [foo] = [];
let [bar, foo] = [1];
// Both assignments were unsuccessful; foo was undefined
Copy the code
object
Values are very common in our programming, like taking values from object obj.
const obj = { a:1.b:2.c:3}; ,,,,const a = obj.a;
const b = obj.b;
const c = obj.c;
Copy the code
But have you noticed that simply fetching the values of three variables in an object requires three lines of code? If we use structure assignment, we only need one line;
const {a,b,c} = obj;
//a:1
//b:2
//c:3
Copy the code
Object deconstruction differs from arrays in one important way. The elements of an array are arranged in order, and the value of a variable is determined by its position. The attributes of an object have no order, and variables must have the same name as the attributes to get the correct value. If the server returns a property name that I don’t want, isn’t the result assignment a hassle? Don’t worry, we can do that. If the server returns the property name a, we need to use the property name B. So we can define it like this:
const {a:b} = obj;
//b:1
Copy the code
Deconstruction failed and the value of the variable is undefined.
let {foo} = {a:1};
//foo:undefined
Copy the code
Data consolidation: Mainly the use of extended operators
An array of
Before merging two arrays, we usually use the following method:
const a = [1.2.3];
const b = [1.5.6];
const c = a.concat(b);/ /,2,3,1,5,6 [1]
Copy the code
Using es6 syntax, we can implement this:
const c = [...a,...b];/ / [6]
Copy the code
However, it should be noted that these two methods are only shallow copies, so be careful when using them.
object
For merging objects, we used to use the following methods:
Const obj1 = {a:1}; Const obj1 = {b:1}; const obj = Object.assgin({}, obj1, obj2); //{a:1,b:1}Copy the code
Using es6 syntax, we can implement this:
constobj = {... obj1,... obj2};//obj:{a:1,b:2}
Copy the code
Template string
So here’s an example.
const name = 'ac';
const score = 79;
let result = ' ';
let desc = 'Exam results'
if(score > 60){
result = `${name}${desc}Pass the `;
}else{
result = `${name}${desc}Fail `;
}
Copy the code
Doesn’t it look like a lot of trouble. Let’s look at another example.
const name = 'ac';
const score = 100;
const result = `${name}${score > 60? ${desc}'qualified':${desc}'Unqualified'}`;
Copy the code
Doesn’t that look a lot easier. The use of template strings has been added in ES6. Inside {} you can put any JavaScript expression, perform operations, and reference object properties.
Common extension methods for arrays
includes
This method returns a Boolean value indicating whether an array contains a given value.
[1.2.3].includes(1);//true
[1.2.3].includes(4);//false
Copy the code
The second argument to this method represents the starting position of the search, which defaults to 0. If the second argument is negative, it represents the reciprocal position, and if it is greater than the array length (for example, if the second argument is -4, but the array length is 3), it is reset to start at 0.
[1.2.3].includes(3.3);//false
[1.2.3].includes(3, -1); // true
Copy the code
This method can be used to optimize the if statement. We often need to determine multiple values in a statement. We might do this:
if(
type == 1 ||
type == 2 ||
type == 3 ||
type == 4) {/ /...
}
Copy the code
Does this seem particularly troublesome? If you use the includes method, we can optimize it as follows:
let condition = [1.2.3.4];
if(condition.includes(type)){}
Copy the code
find()
The find method of an array instance, used to find the first array member that matches the criteria. Its argument is a callback function that is executed by all array members until the first member that returns true is found, and then returned. If there is no qualified member, undefined is returned.
const demo = [1.2.3.4.5];
demo.find((n) = > n > 4);/ / 5
Copy the code
About the use of find in projects. In the project, the search function of some unpaginated lists is realized by the front end, and the search is generally divided into precise search and fuzzy search. Search should also be called filtering, generally we can use filter to achieve.
const a = [1.2.3.4.5];
const result = a.filter( item= >{ return item === 3})Copy the code
For the sake of performance optimization, we generally use find and don’t facilitate arrays once we find the data that matches the criteria.
const a = [1.2.3.4.5];
const result = a.find( item= >{ return item === 3})Copy the code
flat()
Let’s look at an example: a department JSON data, the attribute name is the department ID, the attribute value is the department member ID array collection, now we want to extract the department member IDS into an array collection. Are you still thinking about iterating and then iterating at the end?
const deps = {
'Business division': [1.2.3].'Personnel Department': [4.8.12].'Finance Department': [9.14.79]}
let member = [];
for (let item in deps){
const value = deps[item];
if(Array.isArray(value)){
member = [...member,...value] }
}
/ / member:,2,3,4,8,12,9,14,79 [1]
Copy the code
But if we use the flat method to implement, it will be much more convenient;
const deps = {
'Business division': [1.2.3].'Personnel Department': [4.8.12]}const menber = Object.values(deps).flat();/ /,2,3,4,8,12 [1]
Copy the code
The members of an array are sometimes arrays, and the flat() method is used to “flat10” a nested array into a one-dimensional array. This method returns a new array with no effect on the original data. The default flat() method flattens only one layer. To flatten multiple layers, pass in a specified argument. Such as flat (2);
let demo = [1The [[2.3].4];
demo.flat(2);/ / [1, 2, 3, 4]
Copy the code
If you want to convert to a one-dimensional array regardless of the number of nesting levels, you can use the Infinity keyword as an argument.
[1, [2, [3]]].flat(Infinity)
// [1, 2, 3]
Copy the code
Gets the object property value
To obtain the value of an object attribute, we first need to determine whether the object exists, and then fetch.
const name = obj && obj.name;
Copy the code
If there are too many levels of nesting, the corresponding judgment criteria will be too many to use and look up. We can do this using the optional chain operator in ES6.
constname = obj? .nameCopy the code
Object property name expression
There are two ways to define object properties:
const obj = {
foo:true.name:'ac'
}
obj.age = 25;/ / 1
obj['a' + 'b'] = '123';/ / 2
Copy the code
If the property name changes dynamically, the first approach is obviously not possible. Object attribute name representation is very good for us to solve this problem.
let obj = {};
let index = 1;
obj[`topic${index}`] = 'Here's the content';
Copy the code
Null-value merge operator
When we deal with the business related to the input box, we often judge the scenario where the input box has no value.
if(value ! = =null&& value ! = =undefined&& value ! = =' ') {/ /... }
Copy the code
Using null-value merge operators greatly reduces the writing of judgment conditions
if(value ?? ' '! = =' '){
...
}
Copy the code
?? : Returns the right-hand operand if the left-hand operand is [null] or [undefined], otherwise returns the left-hand operand.
An asynchronous function
Asynchronous functions are common and are generally implemented with promises
const fn1 = () = >{
return new Promise((resolve, reject) = > {
setTimeout(() = > { resolve(1); }, 300); });
}
const fn2 = () = >{
return new Promise((resolve, reject) = > {
setTimeout(() = > { resolve(2); }, 600); }); }
const fn = () = >{
fn1().then(res1= >{
console.log(res1);/ / 1
fn2().then(res2= >{
console.log(res2);/ / 2})})}Copy the code
It is also visually cumbersome to call asynchronous functions in this way. Improvement:
const fn = async() = > {const res1 = await fn1();
const res2 = await fn2();
console.log(res1);/ / 1
console.log(res2);/ / 2
}
Copy the code