8 Practical tips of JavaScript

First, the conversion using Boolean operator!

Sometimes we need to check whether a variable check its existence or check whether there is a valid value value, if it returns a true value. To do this validation, we can be very easy to implement and simple to use! Operator. Variables can be used for detecting !! variable do, as long as the value of the variable: 0, null, "", undefined or NaN will returns false, and vice versa returns true.

Second, the use of the string into a digital +

This technique is very useful, it is very simple, you can pay the string data into digital, but it is only suitable for string data, otherwise it will return NaN.

Third, using operator ||

This feature has a default parameter in ES6. To simulate this feature in the old version of the browser can be used || operator, and the default value as the second parameter. If the first argument returned value is false, then the second value will be considered a default.

Fourth, in the loop cache array.length

This technique is very simple, that when dealing with a very large array cycle performance impact will be very large.

Fifth, the detection object attributes

When you need to detect the presence or absence of some properties, avoid running undefined function or property, the trick becomes useful. If you're going to set some some cross browser compatible code, you may also use this trick. For example, you want to use document.querySelector () to select a id, and it is compatible with IE6 browser, but IE6 browser, this function does not exist, use this operator to detect the presence or absence of this function becomes very useful,

Sixth, get the last element in the array

Array.prototype.slice (begin, end) to obtain the array elements between the begin and end. If you do not set the end parameter, the default will be the length of an array of values ​​as end values. But some students may not know that this function can also accept negative values ​​as parameters. If you set a negative value as the value begin, then you can get the last element of the array.

Seven, an array of cut

This trick is mainly used to lock the size of the array, if used to remove some of the elements in the array, it is very useful. For example, you have an array of 10 elements, but as long as you want before the five elements, then you can array.length = 5 to truncate the array.

Eight, the NodeList into an array

If you run document.querySelectorAll ( "p") function, it may return an array of DOM elements, namely NodeList object. However, this object does not have a function-array, such as sort (), reduce (), map (), filter () and the like. In order to make these native array functions function can also be used above it, you need to convert a list of nodes into an array.

Guess you like

Origin blog.51cto.com/14512197/2446846