12 Very useful JavaScript tips

Source: Internet
Author: User

In this article, we will share 12 tips on JavaScript. These tips may help you solve some problems in your actual work.

Using the !! operator to convert a Boolean value

Sometimes we need to check whether a variable exists or checks if the value has a valid value, and returns the value if it exists true . In order to do this verification, we can use the !! operator to achieve is very convenient and simple. For a variable to be used for !!variable detection, as long as the value of the variable is: 0 ,, null " " , undefined or NaN all will be returned false , the reverse is returned true . such as the following example:

Function account (cash) {This.cash = cash; This.hasmoney =!! Cash }
var account = new account (100.50); Console.log (Account.cash); 100.50console.log (Account.hasmoney); true var Emptyaccount = new account (0); Console.log (Emptyaccount.cash); 0 Console.log (Emptyaccount.hasmoney); False

In this example, as long as account.cash the value 0 is greater than, the account.hasMoney value returned is true .

Use + to convert a string into a number

This technique is very useful, it is very simple, you can convert the string data into a number, but it is only suitable for string data, otherwise it will be returned NaN , such as the following example:

function Tonumber (strnumber) {     

This also applies Date , in this case, it will return the timestamp number:

Console.log (+new Date ()) //1461288164385

and the conditional character

If you have a code like this:

if (conected) {     

You can also abbreviate variables and use them && together with functions, such as the example above, which can be abbreviated as follows:

conected && Login ();

If some properties or functions exist in an object, you can also do this, as shown in the following code:

User && user.login ();

Using || Operators

This feature has default parameters in ES6. To emulate this feature in an older version of the browser, you can use the || operator and pass the default value as the second parameter. If the first parameter returns a value of false , then the second value will be considered a default value. As the following example:

function User (name, age) {     this.name = name | | "Oliver Queen";     

Caching in Loopsarray.length

This is a very simple technique, which will have a very large effect on performance when dealing with a large array loop. Basically, you will write an array of such synchronous iterations:

for (var i = 0; i < Array.Length; i++) {     

If it is a small array, this is good, if you are dealing with a large array, this code will recalculate the size of the array in each iteration, which will cause some delay. To avoid this phenomenon, you can array.length do a cache:

var length = Array.Length; for (var i = 0; i < length; i++) {     

You can also write in this way:

for (var i = 0, length = array.length; i < length; i++) {     

Detecting Properties in Objects

This trick is useful when you need to detect whether some properties exist and avoid running undefined functions or properties. If you're going to set some cross-compatible browser code, you might as well use this little trick. For example, if you want document.querySelector() to use to select one and id make it compatible with the IE6 browser, but this function does not exist in the IE6 browser, it is very useful to use this operator to detect the existence of this function, as in the following example:

if (' Queryselector ' in document) {     document.queryselector ("#id");} else {     

In this example, if document there is no querySelector function, then it is called docuemnt.getElementById("id") .

Gets the last element in the array

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

var array = [1,2,3,4,5,6]; Console.log ( Array.slice (-1//Console.log (Array.slice (-2//  Console.log (Array.slice (-3//

Array truncation

This trick is primarily used to lock the size of an array, which is useful if you are using to delete some of the elements in the array. For example, your array has 10 an element, but you want only the first five elements, then you can truncate the array.length=5 array by. As the following example:

var array = [1,2,3,4,5,6//  3 ////

Replace All

String.replace()The function allows you to replace the string with a string or regular expression, which itself replaces only the first occurrence of the string, but you can use regular expressions /g to simulate replaceAll() function functions:

var string " John John " ; Console.log (string"ana"//Console.log (string"ana"//

Merging arrays

If you are merging two arrays, you will normally use the Array.concat() function:

var array1 = [1,2,3var array2 = [4,5,6 //

Then this function is not suitable for merging two large arrays, because it consumes a lot of memory to store the newly created array. In this case, you can use an Array.pus().apply(arr1,arr2) alternative to create a new array. This method is not used to create a new array, it simply combines the first second number together and reduces the use of memory:

var array1 = [1,2,3var array2 = [4,5,6 //

NodeListConvert an array

If you run the document.querySelectorAll(“p”) function, it may return an array of DOM elements, that is, the NodeList object. However, this object does not have function functions of the array, such as,, sort() reduce() , and map() filter() so on. In order for these native array functions to be used on top of them, you need to convert the list of nodes into arrays. Can be used [].slice.call(elements) to implement:

var elements = Document.queryselectorall ("P"//var //  var arrayelements = Array.  from // This is another the converting NodeList to Array

Shuffle of array elements

For the shuffling of array elements, you do not need to use any external libraries, such as Lodash, as long as you do this:

var list = [1,2,30.5//

Summarize

Now you have learned some useful javascript tips. Hopefully these tips will help you solve some of the problems at work, or this article may help you. If you have some good JavaScript tips, you are welcome to share them with us in the comments.

12 Very useful JavaScript tips

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.