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 skills to use JavaScript?

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

Share

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

This article mainly explains the "easy to use JavaScript skills", the content of the explanation is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "easy to use JavaScript skills" bar!

1. Get the last item of the array

When setting the start and end parameters, Array.prototype.slice (begin,end) has the ability to cut the array. However, if the termination parameter is not set, the feature is automatically set to the maximum value of the array.

This feature accepts negative values, which I don't think many people know, and if you set the starting parameter to a negative number, you get the last few elements of the array:

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

two。 Use | | operator defaults to a certain value

The current ES6 has a default parameter function. To simulate this feature in older browsers, you can default to a value with the | | (OR operator) as the second available parameter.

If the first parameter is returned to false, the second parameter is treated as the default value. Look at this example:

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

3. Reassemble array elements

Want to be able to reorganize array elements without an external tool library like Lodash? Try the following magic function:

Var list= [1Jing 2Jue 3]; console.log (list.sort (function () {Math.random ()-0.5})); / / [2Jing 1JEI 3]

4. Short circuit condition

If you see a code similar to:

If (connected) {login ();}

You can shorten the above code by using a combination of variables (which will be validated) and the & & (AND operator) between functions. For example, the above code can be shortened to one line:

Connected & & login ()

You can do the same to check whether there are properties or functions in the object. Similar to the following code:

User & & user.login ()

5. Intercept array

This technique locks the size of the array and is useful to remove certain elements from the array according to the number of elements you want to set.

For example, if you have an array of 10 elements, but you only want

The first five, then you can intercept the array and make it smaller by setting array.length=5. Take a look at 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]

6. Convert to a number with the + operator

This technique is really great! It is very simple to operate, but only applies to the str function, otherwise it will return to NaN (non-numeric). Take a look at the following example:

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

This technique also applies to dates, in which case it returns to the timestamp:

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

7. Merge array

If you need to merge two arrays, you can use the Array.contat () 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]

However, this function is not a good tool for merging large arrays because it takes up a lot of memory when creating new arrays.

In this case, you can use Array.push.apply (arr1, arr2) instead of creating a new array. This function merges the second array into the first array and does not take up much memory:

Vararray1 = [1Jing 2Jue 3]; var array2 = [4Med 5JEI 6]; console.log (array1.push.apply (array1, array2)); / / [1Jing 2Jing 3MIT 4JI 5JI 6]

8. Cache array.length in a loop

This technique is simple, but it can have a big impact on performance when dealing with large arrays in a loop. In order to iterate over an array, almost everyone writes code like this at the same time:

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

If you're dealing with a small array, that's fine, but if you're dealing with a large array, the code recalculates the size of the array at each iteration of the loop, causing a delay.

To avoid this, you can cache the array.length to be used in a variable instead of calling it at every iteration of the loop:

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

Want to make it shorter? You can write it this way:

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

9. Replace all

The String.replace () function allows you to replace strings with strings and regular expressions; this function can only be replaced for the first time on this machine. However, you can use / g at the end of the regular expression to simulate the replaceAll () function:

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

10. Use it! Operator to a Boolean value

Sometimes, in order to treat a variable as a true value, we need to check whether a variable exists or has a valid value. In this verification process, you can use! (double negative operator).

A simple! variable automatically converts the data to a Boolean, and the variable returns to false only if it contains values such as 0, null, "", undefined, or NaN, otherwise it returns to true.

To understand this process in practice, let's take a look at the following 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 case, if the value of account.cash is greater than zero, then account.hasMoney is true.

11. Convert NodeList to Arrays

If you run the document.querySelectorAll ("p") function, it is likely to return to an array of DOM elements, the NodeList object. But the object does not have all the functions of the array, such as sort (), reduce (), map (), and filter ().

In order to run the above functions and other native array functions, you need to convert NodeList to Arrays. Want to try this technique? You can use the following function: [] .slice.call (elements):

Var elements = document.querySelectorAll ("p"); / / NodeList var arrayElements = [] .slice.call (elements); / / Now the NodeList is an array//This is another way of converting NodeList to Arrayvar arrayElements = Array.from (elements) Thank you for your reading, the above is the content of "easy to use JavaScript skills", after the study of this article, I believe you have a deeper understanding of what good JavaScript skills have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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