Front-end Knowledge: 12 very useful JavaScript tips

Source: Internet
Author: User

Tag: replace string otherwise john EFI www causes parameter prototype function

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

Use !!Operator Conversion 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); Truevar Emptyaccount = new account (0); Console.log (Emptyaccount.cash); 0console.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 +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) {    return +strnumber;} Console.log (Tonumber ("1234")); 1234console.log (Tonumber ("ACB")); NaN

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) {    login ();}

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 ();
Use ||Operator

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";    This.age = Age | | 27;} var user1 = new User (); Console.log (User1.name); Oliver Queenconsole.log (user1.age); 27var user2 = new User ("Barry Allen"); Console.log (User2.name); Barry Allenconsole.log (user2.age); 25
Caching in Loops array.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++) {    console.log (array[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++) {    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 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 {    document.getElementById ("id");}

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)); [6]console.log (-Array.slice (-2)); [5,6]console.log (-Array.slice (-3)); [4,5,6]
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];console.log (array.length); 6array.length = 3;console.log (array.length); 3console.log (array); [A]
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.Replace (/hn/, "Ana"); "Joana John" Console.log (String.Replace (/hn/g, "Ana")); "Joana Joana"
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];

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,3];var array2 = [4,5,6];console.log (array1.push.apply (Array1, array2)); [1,2,3,4,5,6];
Will 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"); Nodelistvar arrayelements = [].slice.call (elements); Now the NodeList are an arrayvar arrayelements = Array.from (elements); 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,3];console.log (List.sort () (function () {math.random ()-0.5})); [2,1,3]
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 want to learn more front-end knowledge, fast-track employment, you can pay attention to the knowledge of the Sea Carpenter Library Internet Academy Front-end course http://www.zhihaijiangku.com

Front-end Knowledge: 12 very useful JavaScript tips

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.