12 very useful JavaScript skills and javascript skills

Source: Internet
Author: User

12 very useful JavaScript skills and javascript skills

In this article, I will share 12 very useful JavaScript skills. These skills can help you reduce and optimize code.

1) Use !! Convert a variable to a Boolean Type

Sometimes, we need to check whether some variables exist or whether they have valid values so that their values are considered true. For this check, you can use | (double negative operator), which can automatically convert any type of data to a Boolean value. Only these variables will return false: 0, null, "", undefined or NaN, and true is returned for all others. Let's take a look at this simple 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 zero, the value of account. hasMoney is true.

2) use + to convert a variable to a number

This conversion is super simple, but it only applies to numeric strings. Otherwise, NaN (not a number) is returned ). Let's take a look at this example:

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

This conversion operation can also act on Date. In this case, it returns the timestamp:

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

3) Short-circuit condition

If you have seen such similar code:

if (conected) {  login(); } 

Then you can use the & (AND operator) between the two variables to shorten the code. For example, the previous code can be reduced to one line:

conected && login(); 

You can also use this method to check whether some attributes or functions exist in the object. Similar to the following code:

user && user.login(); 

4) use | set the default value

The default parameter is available in ES6. To simulate this function in an earlier browser, you can use the | (OR operator) and use the default value as its second parameter. If the first parameter returns false, the second parameter is returned as the default value. Let's take a look at this 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 

5) cache array. length in a loop

This technique is very simple and can avoid a huge impact on performance when processing large arrays cyclically. Almost everyone uses for to traverse an array in a loop like this:

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

If you use a small array, it is fine, but if you process a large array, this code will calculate the size of the array repeatedly in each loop, which will produce a certain delay. To avoid this, You Can cache array. length in the variable so that the cache is used every time in the loop to replace array. length:

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

For the sake of simplicity, you can write as follows:

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

6) Check the attributes of an object.

This technique is useful when you need to check whether some attributes exist to avoid running undefined functions or attributes. If you plan to write cross-browser code, you may also use this technology. For example, we assume that you need to write code compatible with the old version of Internet Explorer 6 and want to use document. querySelector () to obtain certain elements through ID. However, in modern browsers, this function does not exist. Therefore, you can use the in operator to check whether this function exists. Let's take a look at this example:

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

In this case, if there is no querySelector function in the document, it will use document. getElementById () instead.

7) obtain the last element of the array.

Array. prototype. slice (begin, end) can be used to crop arrays. However, if the end parameter is not set, the end function automatically sets the end parameter to the array length value. I think few people know that this function can accept negative values. If you set a negative number for begin, you can get the reciprocal element from the array:

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] 

8) array truncation

This technique can lock the array size, which is very useful for deleting a fixed number of elements in the array. For example, if you have an array containing 10 elements, but you only want to obtain the first five elements, you can set array. length = 5 to the phase array. Let's take a look at this 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] 

9) replace all

The String. replace () function allows String and Regex to be replaced. This function can only replace the first matched String. However, you can add/g at the end of the regular expression to simulate the replaceAll () function:

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

10) Merge Arrays

To merge two arrays, you can 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]; 

However, this function is not suitable for large arrays because it will create a new array and consume a large amount of memory. In this case, you can use Array. push. apply (arr1, arr2), which does not create a new array, but combines the second number into the first array to reduce 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]; 

11) convert NodeList into an array

If you run the document. querySelectorAll ("p") function, it returns an array of DOM elements, that is, the NodeList object. But this object does not have some functions that belong to arrays, such as: sort (), reduce (), map (), filter (). To enable these functions and other native functions of the array, You need to convert NodeList to an array. To perform conversion, you only need to use this function: []. slice. call (elements ):

Var elements = document. querySelectorAll ("p"); // NodeList var arrayElements = []. slice. call (elements); // now the Array has been converted to var arrayElements = Array. from (elements); // another method for converting NodeList into an array

12) shuffling array elements

To shuffles data elements like the external library Lodash, you only need to use this technique:

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

Conclusion

Now you have learned some useful JS skills, which are mainly used to reduce the amount of JavaScript code, some of which are used in many popular JS frameworks, such as Lodash and Underscore. js, Strings. js. If you know other JS skills, please share them!

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.