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 12 concepts to improve JavaScript skills

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article shows you 12 concepts to improve your JavaScript skills, which are concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the details of this article.

JavaScript is a complex language. If you are a senior or junior JavaScript developer, it is important to understand its basic concepts.

1. Variable assignment (value vs reference)

Understanding how JavaScript assigns values to variables can help us reduce some unnecessary bug. If you don't understand this, it may be easy to write code that has been inadvertently changed.

JavaScript always assigns values to variables by value. This part is very important: when the specified value is one of the five basic types of JavaScript (that is, Boolean,null,undefined,String and Number), the actual value is assigned. However, when the specified value is Array,Function or Object, a reference to the object in memory is assigned to the variable.

In the following code snippet, the var2 is assigned using var1. Because var1 is a basic type (String), the value of var2 is equal to the String value of var1 and can be considered completely different from var1 at this time. Therefore, reassigning var2 has no effect on var1.

Next, compare with the object assignment.

If you expect it to be like the primitive type assignment, there is likely to be a problem! If you create a function that inadvertently changes the object, some unexpected behavior will occur.

two。 Closure

Closures are an important JavaScript pattern that allows private access to variables. In this case, createGreeter returns an anonymous function that accesses the parameter greeting (in this case, "Hello"). In subsequent calls, sayHello will have access to this greeting!

In a more realistic scenario, you can imagine an initial function apiConnect (apiKey) that returns some methods that use API key. In this case, apiKey only needs to provide it once.

3. Deconstruction

JavaScript parameter deconstruction is a common way to extract desired attributes from an object.

If you want to extract attributes under a different name, you can use the following ways:

Deconstruction is often also used directly to extract the parameters passed to the function. If you are familiar with React, you may have seen this:

4. Expansion operation

One of the common features of ES6 is to expand (.) Operator, in the following example, Math.max cannot be applied to the arr array because it does not take the array as a parameter, but it can pass in individual elements as parameters. Expand operator. Can be used to extract individual elements of an array.

5. Residual parameter

The remaining parameter syntax looks the same as the unfold syntax, except that the unfold syntax is for structuring arrays and objects, while the remaining parameters are the opposite of the expansion operator, and the remaining parameters collect multiple elements to form an array.

Function myFunc (... args) {console.log (args [0] + args [1]);} myFunc (1,2,3,4); / / 3

The difference between rest parameters and arguments

Arguments is a pseudo array that contains all the arguments

The remaining parameters are standard arrays, and you can use array methods

6. Array method

The JavaScript array method usually provides an incredible and elegant way to perform the required data transformations. As a contributor to StackOverflow, I often see questions about how to manipulate arrays of objects in some way, which is often the perfect use case for array methods.

Map 、 filter 、 reduce

The JavaScript array methods map, filter, and reduce are easily confused, and these are all useful ways to convert arrays or return aggregate values.

Map: returns an array in which each element is converted using the specified function.

Const arr = [1,2,3,4,5,6]; const mapped = arr.map (el = > el + 20); console.log (mapped); / / [21, 22, 23, 24, 25, 26]

Filter: returns an array in which the corresponding elements are included only if the specified function returns true.

Const arr = [1, 2, 3, 4, 5, 6]; const filtered = arr.filter (el = > el = 2 | | el = 4); console.log (filtered); / / [2,4]

Reduce: accumulate by the value specified in the function

Const arr = [1,2,3,4,5,6]; const reduced = arr.reduce ((total, current) = > total + current); console.log (reduced); / / 21find, findIndex, indexOf

Find: returns the first instance that matches the specified criteria. If found, it will not continue to find other matching instances.

Const arr = [1,2,3,4,5,6,7,8,9,10]; const found = arr.find (el = > el > 5); console.log (found); / / 6

Notice again that although all elements after 5 meet the criteria, only the first matching element is returned. When you find a match, you usually break the for loop, which is actually very useful in this case.

FindIndex: this is almost identical to find, but instead of returning the first matching element, it returns the index of the first matching element.

Const arr = ['Nick',' Frank', 'Joe',' Frank']; const foundIndex = arr.findIndex (el = > el = 'Frank'); console.log (foundIndex); / / 1

IndexOf: almost identical to findIndex, but instead of taking a function as an argument, it takes a simple value. You can use this method when you need simpler logic and do not need to use functions to check if there is a match.

Const arr = ['Nick',' Frank', 'Joe',' Frank']; const foundIndex = arr.indexOf ('Frank'); console.log (foundIndex); / / 1push, pop, shift, unshift

Push: this is a relatively simple way to add an item to the end of the array. It modifies the array in place, and the function itself returns the items added to the array.

Let arr = [1,2,3,4]; const pushed = arr.push (5); console.log (arr); / / [1,2,3,4,5] console.log (pushed); / / 5

Pop: this removes the last item from the array. Again, it modifies the array in place, and the function itself returns the items deleted from the array.

Let arr = [1,2,3,4]; const popped = arr.pop (); console.log (arr); / / [1,2,3] console.log (popped); / / 4

Shift: removes the first item from the array. Again, it modifies the array in place. The function itself returns the items deleted from the array.

Let arr = [1,2,3,4]; const shifted = arr.shift (); console.log (arr); / / [2,3,4] console.log (shifted); / / 1

Unshift: adds one or more elements to the beginning of the array. Again, it modifies the array in place. Unlike many other methods, the function itself returns the new length of the array.

Let arr = [1,2,3,4]; const unshifted = arr.unshift (5,6,7); console.log (arr); / / [5,6,7,1,2,3,4] console.log (unshifted); / / 7splice, slice

* * splice:** changes the contents of the array by deleting or replacing existing elements and / or adding new elements, which modifies the array itself.

The following code example means that 0 elements are deleted at position 1 of the array and b is inserted.

Let arr = ['asides,' canals, 'dudes,' e']; arr.splice (1, 0,'b')

Slice: returns a shallow copy of the array from the specified start position and the specified end position. If no end position is specified, the rest of the array is returned. Importantly, this method does not modify the array, but returns the required subset.

Let arr = ['averse,' baked, 'caged,' dashed,'e']; const sliced = arr.slice (2,4); console.log (sliced); / / ['clocked,' d'] console.log (arr); / / ['averse,' baked, 'crested,' dashed,'e'] sort

* * sort:** sorts the array according to the function provided. This method modifies the array in place. If the function returns a negative number or 0, the order remains the same. If a positive number is returned, the element order is swapped.

Let arr = [1,7,3,-1,5,7,2]; const sorter = (firstEl, secondEl) = > firstEl-secondEl; arr.sort (sorter); console.log (arr); / / [- 1, 1, 2, 3, 5, 7, 7] 7. Generators (generator)

The generator is a special behavior, which is actually a design pattern, and we iterate through an ordered set of values by calling the * * next () method. Imagine, for example, using an ergozer to traverse an array [1, 2, 3, 4, 5]. The first call to the next () method returns 1, the second call to the next () method returns 2, and so on. When all the values in the array are returned, calling the next () * * method will return null or false or other possible values to indicate that all the elements in the array have been traversed.

Use the generator to generate unlimited values:

8. Identity operator (= =) and equality operator (= =)

You must know the difference between the identity operator (= =) and the equality operator (= =) in JavaScript! The = = operator performs type conversions before comparing values, while the = operator does not perform any type conversions before comparing values.

Console.log (0 = ='0'); / / true console.log (0 ='0'); / / false9. Object comparison

I see that the mistake made by a novice to JavaScript is to make a direct comparison. The variable points to a reference to the object in memory, not to the object itself! One way to actually compare them is to convert the object to an JSON string. There is a disadvantage: the order of object attributes cannot be guaranteed! A safer way to compare objects is to introduce libraries that specialize in deep object comparisons (for example, lodash's isEqual).

The following objects appear to be equal, but in fact they point to different references.

Const joe1 = {name: 'Joe'}; const joe2 = {name:' Joe'}; console.log (joe1 = joe2); / / false

Instead, the following evaluation is true, because one object is set to be equal to another object, so it points to the same reference (there is only one object in memory).

Const joe1 = {name: 'Joe'}; const joe2 = joe1; console.log (joe1 = joe2); / / true

Instead, the following evaluation is true because one object is set to equal another object, so it points to the same reference (there is only one object in memory).

Const joe1 = {name: 'Joe'}; const joe2 = joe1; console.log (joe1 = joe2); / / true10. Callback function

Many people are intimidated by the JavaScript callback function! They are very simple, for example. The console.log function is passed to myFunc as a callback. It executes when the setTimeout is complete.

Function myFunc (text, callback) {setTimeout (function () {callback (text);}, 2000);} myFunc ('Hello worldview, console.log); / /' Hello worldview 11. Promises

Once you understand the JavaScript callback, you will soon find yourself in "callback hell". At this point, you can use promise to wrap asynchronous logic in promise, resolve on success or reject on failure to use "then" to handle successful cases, and catch to handle exceptions.

12. Async/Await

After you have mastered the use of promise, you may also like async await, which is just a "grammatical sugar" based on promise. In the following example, we create an async function and await greeter promise it.

The above is what the 12 concepts of improving JavaScript skills are. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are 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