11 kinds can not find in most tutorials JavaScript tips


Each time-saving tips when I started to learn JavaScript, I took my place any outside someone else's code, code challenge tutorial I use the site and found a list of all the columns. 

In this article, I will share the tips I think it is particularly useful 11. This article is for beginners, but I hope that even intermediate JavaScript developers can find something new in this list. 

To read more articles please Mengchuo quality GitHub blog, nearly 100 articles a year of high-quality articles waiting for you! 

1 .. filter unique value 
Set object type is introduced in the ES6, with the unfolding operation ... together, we can use it to create a new array that only unique values. 

Array = const [. 1,. 1, 2,. 3,. 5,. 5,. 1] 
const uniqueArray = [... the Set new new (Array)]; 
the console.log (uniqueArray); // the Result: [. 1, 2,. 3, 5] 
before ES6, isolating only the code value involves much more than this. 

This technique is suitable for containing basic types of arrays: undefined, null, boolean, string and number. (If you have an object, function, or other array comprising an array, you need a different approach!) 

2 OR operation with 
the ternary operator is to write a simple (and sometimes not so simple) Fast process conditions statement, as follows : 

X> 100 'Above 100': 'Below 100';? 
X> 100? (X> 200 is 'Above 200 is':? 'the Between 100-200'): 'Below 100';

But sometimes the ternary operator processing will be very complicated. Instead, we can use 'and' && and 'or' || logical operators to more concisely written expression. This is often referred to as "short" or "short-circuit operation." 

How it works 
Suppose we want a return to two or more options. 

Use && returns the first condition is false value. If the calculated value of each operand are true, then a last calculated expression returns. 

One =. 1 the let, TWO = 2, Three =. 3; 
the console.log (Three One && && TWO); // the Result:. 3 
the console.log (null && 0); // the Result: 0 

used to return a first || a condition is true value. If the calculation result of each operand are false, calculated last expression is returned. 

One =. 1 the let, TWO = 2, Three =. 3; 
the console.log (Three One || || TWO); // the Result:. 1 
the console.log (null || 0); // the Result: null 

embodiment a 
Suppose we I want to return the length of a variable, but we do not know the type of the variable. 

We can use if / else statement to check the type of foo is acceptable, but it can become very tedious. Or run can help us simplify operations: 

return (foo || []) length. 
If the variable foo is true, it will be returned. Otherwise, it returns an empty array of length: 0.

Example Two
Have you experienced problems accessing nested object properties? You may not know where the object or whether there is a sub-properties, which may lead to frustrating errors. 

Suppose we want to access a property called data in this.state in, but in our program a successful return before acquisition request, data is undefined. 

We use according to its location, call this.state.data may prevent our application running. To solve this problem, we can be further determine: 

IF (this.state.data) { 
  return this.state.data; 
} the else { 
  return 'Fetching the Data'; 
} 
but it seems repeated. 'Or' operator provides a more elegant solution: 

return (this.state.data || 'Fetching the Data'); 
a new feature: Optional Chaining 
past calling Object property chain, it is easy because a property is not Can not read property xxx of undefined error occurs after the presence of lead. 

That optional chaining is added?. So one operator, it first determines the previous value, if it is null or undefined, calling it the end, returns undefined. 

For example, we can reconstruct the example above is this.state.data?. (). Or, if we focus on whether the state has been defined, we can return this.state? .data.

The proposal is currently in Phase 1, as an experimental feature. You can read it, you can now use your JavaScript by Babel, adding @ babel / plugin-proposal-optional -chaining to your .babelrc file. 

3. Converting to boolean 
addition to the conventional Boolean values true and false, JavaScript also all other values as 'truthy' or 'falsy'. 

Unless otherwise defined, all values in JavaScript are the 'truthy', in addition to 0, "", null, undefined , NaN, of course, false, these are 'falsy' 

We can count by using negative operators easily switching between true and false. It will also be converted to type "boolean". 

isTrue 0 = const;! 
const = IsFalse. 1;! 
const alsoFalse !! = 0; 
the console.log (isTrue); // the Result: to true 
the console.log (typeof to true); // the Result: "Boolean"           
4. converted to string 
to quickly convert a number to a string, we can use the concatenation operator followed by a set of empty quotes + "." 

Val +. 1 = const ""; 
the console.log (Val); // the Result: ". 1" 
the console.log (typeof Val); // the Result: "

int = the let "15"; 
int = int +; 
the console.log (int); // the Result: 15 
the console.log (typeof int); the Result: "Number" 
It may also be used to convert a digital Boolean values, as follows as shown in 

 the console.log (+ to true); // the Return:. 1 
 the console.log (+ to false); // the Return: 0 
in some contexts, + to be interpreted as concatenation operator, rather than the addition operator. When this happens (you want to return an integer rather than floating), you can use two tilde: ~ ~. 

Two consecutive waves effectively negates operation, because - (- n - 1) - 1 = n + 1 - 1 = n. In other words, equal to 15 to -16. 

= ~ ~ int const "15" 
the console.log (int); // the Result: 15 
the console.log (typeof int); the Result: "Number" 
although I can think of many use cases, but bitwise NOT operator can also be used on Boolean: ~ true = -2 and ~ false = -1. 

6. The better performance of the operation 
from the beginning ES7, may be used as a power exponential operator ** shorthand, which is faster than the preparation Math.pow (2, 3). This is a very simple thing, but the reason why it appears in the list, is because not many tutorials updated this operator. 

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

This should not normally used for an index representing the caret confused, but in JavaScript it is the bitwise exclusive OR operator. 

Before ES7, only a power of 2 as the base is present only short, using the bitwise left shift operator << 

Math.pow (2, n-); 
2 << (n--. 1); 
2 ** n-; 
e.g., 2 << 16 3 = equal to 2 ** 16 = 4. 

Fast floating point to integer 7. 
If desired floating-point convert integer, may be used Math.floor (), Math.ceil () or Math.round (). But there is a faster method can be used | (bitwise OR operator) will float truncated to an integer. 

console.log (23.9 |;: 0) // 23 the Result 
-23:; | the Result // console.log (-23.9 0) 
case depends on the processing behavior is positive or negative, so it is best only in certain | under using this shortcut. 

If n is positive, the n | 0 effectively rounded down. If n is negative, the effective upward rounding. More precisely, this action will delete anything after the decimal point, floating-point truncated to an integer. 

~ You can use to get the same rounding effect, as described above, virtually any bit floating-point operator will force an integer. These special operation is efficient because once forced to integer value remains unchanged. 

Delete the last digit 
bitwise OR operator may also be used to delete from the end of any number of integer numbers. This means that we do not need to use this code to switch between types. 

STR = the let "1553"; 
Number The (str.substring (0, str.length -. 1));
Instead, bitwise OR operator can write: 

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

8. the automatic binding class 
we can use the method in the class ES6 arrow notation, and may implicitly by doing so bind. This is usually kept in our class constructor few lines of code, we can happily farewell repeated expressions, e.g. this.myMethod.bind = this.myMethod (the this) 

Import React, {from} the Component React; 
Export default class {Compononent the extends the App 
  constructor (The props) { 
  Super (The props); 
  this.state = {}; 
  } 
the myMethod = () => { 
    ! // This implicitly bound Method IS 
  } 
the render () { 
    return ( 
      <> 
        <div> 
          { this.myMethod ()}  
        </ div>
      </>
    ) 
  } 
}; 

9. array truncate 
end remove from the array if the value, the faster than using the splice (). 

For example, if you know the size of the original array, you can re-define its length property, such as 

the let Array = [0,. 1, 2,. 3,. 4,. 5,. 6,. 7,. 8,. 9]; 
be array.length . 4 =; 
the console.log (Array); // the Result: [0,. 1, 2,. 3] 
this is a particularly elegant solution. However, I found that faster running slice () method of the time. If speed is your main objective, consider: 

the let Array = [0,. 1, 2,. 3,. 4,. 5,. 6,. 7,. 8,. 9]; 
Array Array.slice = (0,. 4); 
the console.log (array); // the Result: [0,. 1, 2,. 3] 
10. the last acquired an array 
array method slice () can accept negative integer, if it is provided, it will accept the value end of the array, rather than the beginning of the array of values. 

Array = the let [0,. 1, 2,. 3,. 4,. 5,. 6,. 7,. 8,. 9]; 
the console.log (Array.slice (-1)); // the Result: [. 9]  
the console.log (Array .slice (-2)); // Result : [8, 9]
the console.log (Array .slice (-3)); // the Result: [. 7,. 8,. 9] 

11. The formatting codes JSON
Finally, you may have been previously used JSON.stringify, but did you realize that it can also help you indent JSON? 

the stringify () method has two optional parameters: a replacer function, and can be used for a space JSON filtered value displayed. 

the console.log (the JSON.stringify ({Alpha: 'A', Beta: 'B'}, null, '\ T')); 
// the Result: 
// '{ 
// "Alpha": A, 
// " Beta ": B 
//} ' 
original: https: //medium.com/@bretcamer ...

  

Guess you like

Origin www.cnblogs.com/zhangheliang/p/10943018.html