This time we will share 11 JavaScript tips that are not often mentioned in tutorials, but are often overlooked in our daily work.Copy the code
1. 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 array = [1, 2, 3, 3, 5, 5, 1]; const uniqueArray = [...new Set(array)]; console.log(uniqueArray); // [1, 2, 3, 5] copy codeCopy 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.
2. Short-circuit Evaluation
The ternary operator is a very convenient and fast way to write some simple logical statements,
x > 100 ? 'Above 100' : 'Below 100'; x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100'; Copy the codeCopy the code
But sometimes when the logic is complicated, the ternary operators can be hard to read to write. This time, we can use logic and (&) and the logic or (| |) operator to rewrite our expression.
The logic and and or operators always evaluate their operands first, and evaluate their right-hand operands only if the result of the logical expression cannot be determined by the value of the left-hand operand alone. This is called short-circuit Evaluation.
The working principle of
The and (&&) operator will return the first false/ ‘falsy’ value. When all operands are true, the result of the last expression is returned.
let one = 1, two = 2, three = 3; console.log(one && two && three); // Result: 3 console.log(0 && null); // Result: 0 copies the codeCopy the code
Or (| |) operator returns the first true/’ truthy value. When all operands are false, the result of the last expression is returned.
let one = 1, two = 2, three = 3; console.log(one || two || three); // Result: 1 console.log(0 || null); // Result: null copy codeCopy the code
Scenario, for example,
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'; } Duplicate codeCopy the code
But we can abbreviate this logical processing in the way above
return (this.state.data || 'Fetching Data'); Copy the codeCopy the code
Contrast found this way more concise and convenient.
3, convert Boolean
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" copies the codeCopy the code
4. Convert to String
We can convert a variable of type number to a string using the + concatenation operator.
const val = 1 + ""; console.log(val); // Result: "1" console.log(typeof val); // Result: "string" copy codeCopy the code
5. Convert 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" copies the codeCopy 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" copies the codeCopy 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 codeCopy 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 <<
Math.pow(2, n); math.pow (2, n); 2 << (n - 1); 2**n; Copy the codeCopy 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.
The console. The log (23.9 | 0); / / the Result: 23 console. The log (23.9 | 0); // Result: -23 Copy codeCopy 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.
Usage scenarios
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 codeCopy 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. The console log | 0 (1553/1000) / / Result: 1 copy codeCopy the code
8. Automatic binding in classes
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 codeCopy the code
9. Intercept an 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 codeCopy 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 codeCopy the code
Get the last element 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(array.slice(-1)); // Result: [9] console.log(array.slice(-2)); // Result: [8, 9] console.log(array.slice(-3)); // Result: [7, 8, 9] copy codeCopy the code
Format the 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}' copy codeCopy the code
** Overall, I hope you found these tips as useful when you saw them as I did when I first saw them. If you have found their own tips, also hope to be able to write down in the message, we share together. I formed a front-end learning exchange group to learn front-end technology. To share learning materials, want to join the learning partners can click the link to join the group chat click the link to join the group chat [Web front-end technology group] : jq.qq.com/?_wv=1027&k…