Share 12 very practical JavaScript tips _javascript Tips

Source: Internet
Author: User
Tags shuffle

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

Use!! Operator Conversion Boolean value

Sometimes we need to check whether the value has a valid value for a variable or not, and return a true value if it exists. In order to do such verification, we can use!! Operators to achieve is very convenient and simple. For variables you can use!! Variable do detection, as long as the value of the variable is: 0, NULL, "", Undefined, or Nan will return false, otherwise return true. Like the following example:

Function account (Cash) { 
  This.cash = cash; 
  This.hasmoney =!! Cash; 
} 
var account = new account (100.50); 
Console.log (Account.cash); 100.50 
Console.log (Account.hasmoney);//True 
 
var emptyaccount = new account (0); 
Console.log (Emptyaccount.cash); 0 

In this example, the value returned by Account.hasmoney is true as long as the value of the Account.cash is greater than 0.

Use + to convert strings to numbers

This technique is very useful, simple enough to convert string data to numbers, but it is only suitable for string data, otherwise it will return Nan, such as the following example:

function Tonumber (strnumber) {return 
  +strnumber; 
} 
Console.log (Tonumber ("1234")); 1234 
Console.log (Tonumber ("ACB"));//NaN

This also applies to date, in this case, it will return a timestamp number:

Copy Code code as follows:
Console.log (+new Date ())//1461288164385 and conditional character

If you have a piece of code like this:

if (conected) {
login (); 

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

Copy Code code as follows:
conected && Login ();

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

Copy Code code as follows:
User && user.login ();

Use | | Operator

There is a feature of default parameters in ES6. To simulate this feature in an older version of the browser, you can use the | | Operator and passes the default value as the second argument. If the first argument returns false, the second value is considered to be a default value. As the following example:

function User (name, age) { 
  this.name = name | | "Oliver Queen"; 
  This.age = Age | | ; 
} 
var user1 = new User (); 
Console.log (User1.name); Oliver Queen 
Console.log (user1.age);// 
 
var user2 = new User ("Barry Allen"); 
Console.log (User2.name); Barry Allen 

Caching Array.Length in Loops

This technique is very simple, and the performance impact will be very large when dealing with a large array loop. Basically, you'll write an array of such synchronized iterations:

for (var i = 0; i < Array.Length i++) { 
  console.log (array[i]); 

If it's a small array, that's good, if you're dealing with a large array, this code will recalculate the size of the array in each iteration, which can cause some delays. To avoid this, you can make Array.Length a cache:

var length = Array.Length; 
for (var i = 0; i < length; i++) { 
  console.log (array[i]); 
}

You can also write in this way:

for (var i = 0, length = Array.Length i < length; i++) { 
  console.log (array[i]); 

Detecting properties in an object

This tip is useful when you need to detect whether some properties exist and avoid running undefined functions or properties. If you're going to make some cross compatible browser code, you might want to use this tip. For example, if you want to use Document.queryselector () to select an ID and make it compatible with IE6 browsers, but this function does not exist in the IE6 browser, it is useful to use this operator to detect whether the function exists, as in the following example:

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

In this example, if the document does not have a queryselector function, then Docuemnt.getelementbyid ("id") is invoked.

Gets the last element in the array

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

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

Array truncation

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

var array = [1,2,3,4,5,6]; 
Console.log (Array.Length); 6 
array.length = 3; 
Console.log (Array.Length); 3 
console.log (array);//[1,2,3]

Replace All

The String.Replace () function allows you to replace a string with a string or regular expression, which replaces only the first occurrence of the string, but you can simulate the ReplaceAll () function by using the/g of the regular expression multiple:

var string = "John John"; 
Console.log (String.Replace (/hn/, "Ana")); "Joana John." 

Merging arrays

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

var array1 = [1,2,3]; 
var array2 = [4,5,6]; 
Console.log (Array1.concat (array2)); [1,2,3,4,5,6]; 

This function is then 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 Array.pus (). Apply (ARR1,ARR2) instead of creating a new array. This method is not used to create a new array, which simply combines the first second number together and reduces the use of memory:

var array1 = [1,2,3]; 
var array2 = [4,5,6]; 
Console.log (Array1.push.apply (Array1, array2)); [1,2,3,4,5,6]; 

Convert NodeList to an array

If you run the Document.queryselectorall ("P") function, it may return an array of DOM elements, which is the NodeList object. However, this object does not have function functions of an array, such as sort (), reduce (), map (), filter (), and so on. In order for these native array function functions to be used on them, the node list needs to be converted into arrays. You can use [].slice.call (elements) to implement:

var elements = Document.queryselectorall ("P"); NodeList 
var arrayelements = [].slice.call (elements);//Now The nodelist are an array 

Shuffle of array elements

For the shuffle 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,3]; 
Console.log (List.sort (function () {math.random ()-0.5})); [2,1,3]

Summarize

Now you've learned some useful JavaScript tips. Hopefully these tips will help you solve some of the problems at work, or you can say this article is helpful to you. If you have some excellent JavaScript tips, please share them with us in the comments.

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.