1,… Expansion operator

Let’s say I have a summation function,

let sum = function(a,b,c){
    return a+b+c;
}
Copy the code

And an array variable

let arr = [1.2.3];
Copy the code

Now if I want to sum an array, how do I write it? Your brain’s first instinct may be to traverse, but is there an easier way? The answer is yes.

sum(... arr); // Use the es6 expansion operatorCopy the code

What is an expansion operator? Read the official explanation:

Spread syntax: array expression or string can be expanded at the syntactic level during function call/array construction; You can also construct literal objects by expanding the object expression key-value. [1, 2, 3] {name: “MDN “}

So the question is, what if you can do it without the expansion operator? Yes.

sum.apply(null,arr); 
Copy the code

###2, filter unique values

The Set type is new in ES6. It is similar to an array, but the values of the members are unique and there are no duplicate values. Combined with extension operators (…) We can create a new array to filter out duplicate values of the original array.

const marray=[1.2.3.4.52.3.2];
let afterArray=[new Set(...marray)]
Copy the code

Prior to ES6, we needed a lot more processing code to implement this functionality. This technique applies only when the values in an array are of type: undefined, NULL, Boolean, string, number. If object, function, or array is included, it is not applicable.

###3, the ternary operator

When we request data from the server, we use the data in another location, but the state of the retrieved data is not known, such as when we access the data property of this.state. According to the conventional way, we will judge the validity of this.state.data first, and then discriminate according to the validity.

if (this.state.data) {
  return this.state.data;
} else {
  return 'Fetching Data';
}
Copy the code

Can be condensed to

return (this.state.data || 'Fetching Data');
}
Copy the code

###4, convert to bool

Normal Boolean values are only true and false, but in JavaScript we can think of other values as’ truthy ‘or’ falsy ‘.

With the exception of 0, “”, null, undefined, NaN and false, everything else can be considered ‘truthy’.

We can use the negative operator! Convert a list of variables to Boolean.

const isTrue  = !0;
const isFalse = !1;
const alsoFalse = !!0;

console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"
Copy the code

###5, convert to number

Alternatively, we can convert a string variable back to a number variable using the addition operator +.

let int = "15";
int = +int;

console.log(int); // Result: 15
console.log(typeof int); Result: "number"
Copy the code

In some contexts, + will be interpreted as the join operator, not the addition operator. When this happens (you want to return an integer, not a floating point number), you can use two tilde :~~. (Note that the format is in English)

A tilde ~, called the bitwise nonoperator, is equivalent to -n-1. So minus 15 is minus 16.

Two negation operations are valid using ~~. That’s because minus n minus 1 minus 1 is n plus 1 minus 1 is n. So minus 16 is equal to 15

const int = ~~"15"

console.log(int); // Result: 15
console.log(typeof int); Result: "number"
Copy the code

###6, quick exponentiation

Starting with ES7, we can use the exponentiation operator ** as a shorthand for exponentiation, which is faster than math.pow (2, 3) before. This is a very simple and useful point, but most tutorials are not devoted to it.

console.log(2 ** 3); // Result: 8
Copy the code

This should not be confused with the ^ symbol, which is usually used to represent exponents, but is the bitxor operator in JavaScript.

Prior to ES7, power abbreviations relied mainly on the bit left shift operator <<.

// The following expressions are equivalent to math.pow (2, n);
2 << (n - 1);
2**n;
Copy the code

Note that 2 << 3 = 16 is equivalent to 2 ** 4 = 16

###7, fast Float to Integer

We can normally convert float to integer using math.floor (), math.ceil (), and math.round ().

But there’s a faster way to use | (or operators) will float truncated as an integer.

console.log(23.9 | 0);  // Result: 23
console.log(23.9 | 0); // Result: - 23
Copy the code

| behavior depends on the processing is positive or negative, so best only in certain cases using this shortcut.

If n is a positive number, n | 0 rounding down effectively. If n is negative, it effectively rounds up. To be more precise, the result of this operation is to simply delete the content after the decimal point and truncate the floating point number to an integer, which is different from the other methods mentioned above.

You can also use ~~ to get the same rounding effect; as mentioned above, virtually any bitwise operator forces a floating point number to be an integer. These special operations work because once an integer is forced, the value remains the same.

###8, fast Float to Integer

We can normally convert float to integer using math.floor (), math.ceil (), and math.round ().

But there’s a faster way to use | (or operators) will float truncated as an integer.

console.log(23.9 | 0);  // Result: 23
console.log(23.9 | 0); // Result: - 23
Copy the code

| behavior depends on the processing is positive or negative, so best only in certain cases using this shortcut.

If n is a positive number, n | 0 rounding down effectively. If n is negative, it effectively rounds up. To be more precise, the result of this operation is to simply delete the content after the decimal point and truncate the floating point number to an integer, which is different from the other methods mentioned above.

You can also use ~~ to get the same rounding effect; as mentioned above, virtually any bitwise operator forces a floating point number to be an integer. These special operations work because once an integer is forced, the value remains the same.

Using scene bits or operators can be used to remove any number of digits from the end of an integer. This means we don’t have to use such code to convert between types.

let str = "1553"; 
Number(str.substring(0, str.length - 1));
Copy the code

Instead, we can implement our functionality in the following ways

console.log(1553 / 10   | 0)  // Result: 155
console.log(1553 / 100  | 0)  // Result: 15
console.log(1553 / 1000 | 0)  // Result: 1
Copy the code

###9, automatic binding in the category

We can implement invisible binding scopes in our classes by using the arrow functions added to ES6. Following the previous treatment, we need to explicitly bind the method we wrote, like this.mymethod = this.mymethod.bind (this). When we have a lot of methods in our class, we add a lot of binding code. Now we can simplify this process by using arrow functions.

import React, { Component } from React; export default class App extends Compononent { constructor(props) { super(props); this.state = {}; } myMethod (int x) = () = > {/ / implicit binding} render () {return (< > < div > {enclosing myMethod (int x) (the)} < / div > < / a >)}};Copy the code

###10, intercept the array

If you want to remove values from the end of an array, there are faster alternatives than using splice().

For example, if you know the length of the original array, you can intercept it by redefining its Length attribute.

let array = [0.1.2.3.4.5.6.7.8.9];
array.length = 4;
console.log(array); // Result: [0.1.2.3]
Copy the code

This is a particularly neat solution. However, the slice() method is faster to run. If speed is your main goal, consider using the following methods.

let array = [0.1.2.3.4.5.6.7.8.9];
array = array.slice(0.4);

console.log(array); // Result: [0.1.2.3]
Copy the code

###11 gets the element of the reciprocal of the array

The array method slice() can accept negative integers and, if provided, will truncate values from the end of the array, not the beginning.

let array = [0.1.2.3.4.5.6.7.8.9];
console.log(arraynew.slice(- 1)); / / output [9]
console.log(arraynew.slice(2 -)); / / output [8.9]
console.log(arraynew.slice(4 -)); / / output [6.7.8.9]
Copy the code

###12, format JSON code

We probably use json.stringify a lot when dealing with jSON-related processing, but are you aware that it can help indent JSON?

The stringify() method takes two optional arguments: a replacer function, which can be used to filter displayed JSON, and a space value.

The space value takes an integer representing the number of Spaces needed or a string (such as ‘\t’ to insert tabs), which makes it much easier to read the retrieved JSON data.

console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t')); // Result: // '{ // "alpha": A, // "beta": B // }' console.log(arraynew.slice(-4)); / / output,7,8,9 [6]Copy the code