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 concepts that make JavaScript development easier?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "what are the concepts that make JavaScript development easier?" the content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what concepts make JavaScript development easier.

1. Variable assignment (values and references)

JavaScript always assigns values to variables by value. When the specified value is one of the five primitive types of JavaScript (that is, Boolean, null, undefined, String, and Number), the actual value is assigned to the variable. However, when the specified value is Array, Function, or Object, the object reference of memory is allocated to the variable.

In the following code snippet, use var1 to assign a value to var2. Because var1 is a basic type (String), the value of var2 is equal to the String value of var1, but at this point you can think that var2 is completely different from var1. Therefore, reassigning var2 has no effect on var1.

Let var1 ='My string';let var2 = var1;var2 ='My new string';console.log (var1); / /'My string'console.log (var2); / /'My new string'

We compare it with object assignment.

Let var1 = {name: 'Jim'} let var2 = var1;var2.name =' John';console.log (var1); / / {name: 'John'} console.log (var2); / / {name:' John'}

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 can be used to access private variables. In the following example, createGreeter returns an anonymous function that accesses the parameter greeting (in this case, "Hello"). In subsequent calls, sayHello will have access to this greeting!

Function createGreeter (greeting) {return function (name) {console.log (greeting +','+ name);}} const sayHello = createGreeter ('Hello'); sayHello (' Joe'); / / Hello, Joe

In a more realistic scenario, you can imagine an initialization function apiConnect (apiKey) that returns some methods that use API keys. In this case, you only need to provide the apiKey once.

Function apiConnect (apiKey) {function get (route) {return fetch (`${route}? key=$ {apiKey}`);} function post (route, params) {return fetch (route, {method: 'POST', body: JSON.stringify (params), headers: {' Authorization': `Bearer ${apiKey} `})} return {get, post}} const api = apiConnect ('my-secret-key') / / No need to include the apiKey anymoreapi.get ('http://www.example.com/get-endpoint');api.post('http://www.example.com/post-endpoint', {name:' Joe'})

3. Deconstruction

JavaScript parameter deconstruction is a common method to extract attributes from objects.

Const obj = {name: 'Joe', food:' cake'} const {name, food} = obj;console.log (name, food); / / 'Joe'' cake'

If you need to extract attributes under a different name, you can specify them using the following format.

Const obj = {name: 'Joe', food:' cake'} const {name: myName, food: myFood} = obj;console.log (myName, myFood); / / 'Joe'' cake'

In the following example, the deconstruction is used to pass the person object to the introduce function. In other words, deconstruction can (and often) be used directly to extract the parameters passed to the function. If you are familiar with React, you may have seen this!

Const person = {name: 'Eddie', age: 24} function introduce ({name, age}) {console.log (`Ichimm ${name} and Ichimm ${age} years old! `);} console.log (introduce (person)); / / "I'm Eddie and I'm 24 years old!"

4. Spread syntax

In the following example, Math.max cannot directly accept an arr array because its parameters are not of an array type, but can take individual elements of the array as parameters. Unfold operator... Can be used to extract individual elements of an array.

Const arr = [4,6,-1,3,10,4]; const max = Math.max (.. arr); console.log (max); / / 10

5. Variable length parameter (rest) syntax

You can use it to put any number of arguments passed to the function into an array!

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

6. Array method

The JavaScript array method usually provides you with an incredibly 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 one way or another. This is often the perfect use case for array methods.

Map 、 filter 、 reduce

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: accumulates values based on a given function.

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

Find 、 findIndex 、 indexOf

Find: returns the first instance that matches the specified criteria, and does 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

Although all elements after 5 meet the criteria, only the first matching element is returned.

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 exactly the same as findIndex, but its argument is not a function, but a simple value.

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

Push 、 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: removes the last item from the array. Similarly, it modifies the array in place. 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. Similarly, 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. Similarly, it modifies the array in place. Unlike other methods, the function itself returns the latest 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); / / 7

Splice 、 slice

Splice: modify the contents of an array by deleting or replacing existing elements or adding new elements. This method also modifies the array in place.

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 and end positions. If no end position is specified, the rest of the array is returned. This method does not modify the array, but just 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. Generator

Don't be afraid to see *. The generator function specifies what value will be generated the next time next () is called. You can either generate a limited number of value (the final call to next () returns undefined), or you can use a loop to generate an unlimited number of value.

Function* greeter () {yield 'Hi'; yield' How are you?'; yield 'Bye';} const greet = greeter (); console.log (greet.next () .value); / /' Hi'console.log (greet.next () .value); / / 'How are you?'console.log (greet.next () .value); / /' Bye'console.log (greet.next () .value); / / undefined

Use the generator to generate unlimited values:

Function* idCreator () {let I = 0; while (true) yield iTunes;} const ids = idCreator (); console.log (ids.next () .value); / / 0console.log (ids.next () .value); / / 1console.log (ids.next () .value); / / 2Accord / etc...

8. = and =

Be sure to know the difference between the = = operator and the = operator in JavaScript! The = = operator performs type conversion before comparison, while the = = operator does not cast before comparison.

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

One of the mistakes that novices to JavaScript tend to make is to compare objects directly. Variables are generally references to objects in memory, not to the object itself! One way to compare objects is to convert them to JSON strings. But this has one drawback: there is no guarantee of the order of object properties! A more secure approach is to use libraries that specialize in deep object comparisons (such as lodash's isEqual).

The following objects look the same, but they actually point to different references.

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

Instead, the following result is true, because one object is used to assign a value to the other object, and they all point 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 actually very simple, please see the following example. The console.log function is passed to myFunc as a callback and executes when setTimeout is complete.

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

Once you understand the JavaScript callback, you will soon find yourself in "callback hell". You can use promise at this time! Wrap asynchronous logic in promise, use "then" to handle successful cases, and use "catch" to handle exceptions.

Const myPromise = new Promise (function (res, rej) {setTimeout (function () {if (Math.random ())

< 0.9) { return res('Hooray!'); } return rej('Oh no!'); }, 1000);});myPromise .then(function(data) { console.log('Success: ' + data); }) .catch(function(err) { console.log('Error: ' + err); }); // If Math.random() returns less than 0.9 the following is logged:// "Success: Hooray!"// If Math.random() returns 0.9 or greater the following is logged:// "Error: On no!"12. Async/Await 在掌握了 promise 的用法后,你可能也会喜欢 async await,它只是一种基于 promise 的"语法糖"。在下面的示例中,我们创建了一个 async 函数,并 await greeter promise。 const greeter = new Promise((res, rej) =>

{setTimeout () = > res ('Hello worldview'), 2000);}) async function myFunc () {const greeting = await greeter; console.log (greeting);} myFunc (); / / 'Hello worldview' Thank you for your reading, the above is the content of "what are the concepts that make JavaScript development easier?" after the study of this article, I believe you have a deeper understanding of the concept of making JavaScript development easier, 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