Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the very practical JavaScript tips?

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly shows you "what are the very practical JavaScript tips", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "what are the very practical JavaScript tips" this article.

Use! Operator to convert Boolean values

Sometimes we need to check for the existence of a variable or check whether the value has a valid value, and return the true value if it exists. In order to do such a verification, we can use! Operator to implement is very convenient and simple. For variables, you can use! variable to detect, as long as the value of the variable is: 0, null, "", undefined, or NaN will return false, and vice versa. For example, 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 console.log (emptyAccount.hasMoney); / / false

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

Convert a string to a number using +

This technique is very useful, it is very simple, you can convert string data into 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, which in this case will return a timestamp number:

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

Union condition character

If you have a piece of code like this:

If (conected) {login ();}

You can also abbreviate variables and connect them with functions using & &, such as the example above, which can be simplified like this:

Conected & & login ()

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

User & & user.login ()

Use the | | operator

There is a default parameter feature in ES6. To simulate this feature in older browsers, you can use the | operator and pass in the default value as the second parameter. If the value returned by the * * parameter is false, the second value will be considered as a default value. Such 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 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 simple, and it will have a great impact on performance when dealing with a large array loop. Basically, everyone will write an array of synchronous iterations like this:

For (var I = 0; I < array.length; iTunes +) {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 at each iteration, which will cause some delay. To avoid this, you can make a cache of array.length:

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

You can also write something like this:

For (var I = 0, length = array.length; I < length; iTunes +) {console.log (array [I]);}

Detect attributes in an object

This tip is useful when you need to detect the existence of some properties and avoid running undefined functions or properties. If you plan to order some cross-compatible browser code, you may also use this trick. 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 IE6 browsers, 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 the querySelector function does not exist in document, then docuemnt.getElementById ("id") is called.

Get an element in the array

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

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

Array truncation

This tip is mainly used to lock the size of the array, which 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 the first five elements, you can truncate the array through array.length=5. Such as the following example:

Var array = [1Jing 2 Jing 3 Jing 4 Jing 5 Jue 6]; console.log (array.length); / / 6 array.length = 3; console.log (array.length); / / 3 console.log (array); / / [1Jing 2 Jing 3]

Replace all

The String.replace () function allows you to replace strings with strings or regular expressions. This function itself only replaces strings that appear * times, but you can use the / g in the regular expression to simulate the function of the replaceAll () function:

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

Merge array

If you want to merge two arrays, you will normally use the Array.concat () function:

Var array1 = [1Jing 2 Jue 3]; var array2 = [4 Jet 5 Jol 6]; console.log (array1.concat (array2)); / / [1 Jing 2 Jing 3 Jing 4 Ji 5 Ji 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 Array.pus (). Apply (arr1,arr2) instead of creating a new array. This method is not used to create a new array, it simply combines * second numbers together, while reducing memory usage:

Var array1 = [1Jing 2Jue 3]; var array2 = [4Med 5JEI 6]; console.log (array1.push.apply (array1, array2)); / / [1Jing 2Jing 3MIT 4JI 5JI 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. But this object does not have the function of an array, such as sort (), reduce (), map (), filter (), and so on. In order for these native array functions to be used on it, you need to convert the list of nodes into an array. You can use [] .slice.call (elements) to do this:

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

Shuffle of array elements

For shuffling array elements, you don't need to use any external libraries, such as Lodash, just do this:

Var list = [1Jing 2jue 3]; console.log (list.sort (function () {Math.random ()-0.5})); / / [2Jing 1Jol 3] above are all the contents of this article entitled "what are the very practical JavaScript Tips?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report