Share 12 very useful JavaScript tips and javascript tips

Source: Internet
Author: User

Share 12 very useful JavaScript tips and javascript tips

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

Use !! Operator to convert boolean values

Sometimes we need to check whether a variable exists or whether the value has a valid value. If so, true is returned. For such verification, we can use it !! Operators are very convenient and simple to implement. You can use variables !! Variable checks. If the value of a variable is 0, null, "", undefined, Or NaN, false is returned, and true is returned. For 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 console.log(emptyAccount.hasMoney); // false 

In this example, if the value of account. cash is greater than 0, the value returned by account. hasMoney is true.

Use + to convert a string to a number

This technique is very useful. It is very simple and can convert string data into numbers. However, it is only applicable to string data. Otherwise, NaN is returned, for example:

function toNumber(strNumber) {   return +strNumber; } console.log(toNumber("1234")); // 1234 console.log(toNumber("ACB")); // NaN

This applies to Date. In this example, it returns a timestamp Number:

Copy codeThe Code is as follows: console. log (+ new Date () // 1461288164385 with a condition character

If you have a piece of code like this:

if (conected) {login(); } 

You can also abbreviated variables and connect them with functions. For example, the preceding example can be abbreviated as follows:

Copy codeThe Code is as follows: conected & login ();

If some attributes or functions exist in an object, you can check them as follows:

Copy codeThe Code is as follows: user & user. login ();

Use | Operator

ES6 has the default parameter feature. To simulate this feature in earlier browsers, you can use the | Operator and pass the default value as the second parameter. If the value returned by the first parameter is false, the second value is considered as a default value. For example:

function User(name, age) {   this.name = name || "Oliver Queen";   this.age = age || 27; } var user1 = new User(); console.log(user1.name); // Oliver Queen console.log(user1.age); // 27  var user2 = new User("Barry Allen", 25); console.log(user2.name); // Barry Allen console.log(user2.age); // 25 

Cache array. length in a loop

This technique is very simple. when processing a large array loop, it will have a very huge impact on performance. Basically, everyone will write an array of such synchronization iterations:

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

This is good if it is a small array. If you want to process a large array, this code recalculates the array size in each iteration, this will cause some delays. To avoid this problem, you can cache array. length as follows:

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

You can also write it like this:

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

Property in the detection object

This tip is useful when you need to check whether some attributes exist to avoid running undefined functions or attributes. If you plan to develop cross-compatible browser code, you may also use this tip. For example, you want to use document. querySelector () to select an id and make it compatible with the IE 6 browser. However, this function does not exist in the IE 6 browser, it is very useful to use this operator to check whether the function exists, as shown in the following example:

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

In this example, if the document does not have the querySelector function, docuemnt. getElementById ("id") is called ").

Obtain the last element in the array.

Array. prototype. slice (begin, end) is used to obtain the Array elements between begin and end. If you do not set the end parameter, the default Length Value of the array is treated as the end value. However, some users may not know that this function can accept negative values as parameters. If you set a negative value as the value of begin, you can obtain the last element of the array. For example:

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

Array truncation

This tip is mainly used to lock the array size. It is very useful if it is used to delete some elements in the array. For example, if your array has 10 elements, but you only want to use the first five elements, you can use array. length = 5 to truncate the array. For 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

String. the replace () function allows you to use a string or regular expression to replace a string. This function only replaces the string that appears for the first time. However, you can use the/g in many regular expressions to simulate replaceAll () function:

var string = "john john"; console.log(string.replace(/hn/, "ana")); // "joana john" console.log(string.replace(/hn/g, "ana")); // "joana joana" 

Merge Arrays

If you want to merge two arrays, you usually 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]; 

Then this function is not suitable for merging two large arrays, because it will consume a lot of memory to store the newly created array. In this case, you can use Array. pus (). apply (arr1, arr2) to create a new Array. This method is not used to create a new array, but to combine the first and second numbers and reduce the memory usage:

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, that is, the NodeList object. However, this object does not have array functions, such as sort (), reduce (), map (), and filter. To enable these native array functions to be used on them, you need to convert the node list to an array. You can use []. slice. call (elements) to implement:

var elements = document.querySelectorAll("p"); // NodeList var arrayElements = [].slice.call(elements); // Now the NodeList is an array var arrayElements = Array.from(elements); // This is another way of converting NodeList to Array 

Shuffling array elements

You do not need to use any external libraries for shuffling array elements, such as Lodash:

var list = [1,2,3]; console.log(list.sort(function() { Math.random() - 0.5 })); // [2,1,3]

Summary

Now you have learned some useful JavaScript tips. I hope these tips can help you solve some problems at work, or this article will help you. If you have some excellent JavaScript tips, please share them with us in your comments.

Related Article

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.