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

Case Analysis of javascript characteristics

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

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "javascript feature case analysis". The editor shows you the operation process through the actual case, and the operation method is simple, fast and practical. I hope this "javascript feature case analysis" article can help you solve the problem.

Javascript features are: 1, expansion operator; 2, remaining parameters; 3, string interpolation; 4, abbreviated properties; 5, method properties; 6, deconstruction assignment; 7, array methods; 8, modules; 9, Promises+Async/Await;10, arrow functions and dictionary scope.

This article operating environment: windows7 system, javascript1.8.5 version, Dell G3 computer.

What are the features of javascript?

Ten super useful JS features

The original work of Chris Noring, the translation is reproduced from New Frontend.

You may have just started using JavaScript, or you may have just used it occasionally. In any case, JavaScript has changed a lot, and some features are well worth using. This article introduces some features that, in my opinion, a serious JavaScript developer uses more or less every day.

Unfold operator

As the name implies, the expansion operator (...) before an object or array expands a structure into a list. Show me:

Let firstHalf = ['one',' two']; let secondHalf = ['three',' four',... firstHalf]

Isn't this elegant and concise? If we don't need the unfold operator, we have to write:

Let firstHalf = ['one',' two']; let secondHalf = ['three',' four']; for (var iTun0, I acc + curr, 0);}

As mentioned earlier,... remaining collects the remaining parameters and provides us with the naming of these parameters, making it clear that we intend to process the remaining parameters. I remember that ES5 already has arguments at the latest, but few people know about it.

String interpolation

Have you ever seen a sentence like this?

Class Product {constructor (name, description, price) {this.name = name; this.description = description; this.price = price;} getDescription () {return "Full description\ n" + "name:" + this.name + "description:" + this.description}}

Of course, I'm referring to the poor readability of the multi-long statement in the getDescription () method. A similar phenomenon exists in most programming languages. Fortunately, JavaScript is one of the languages that provide string interpolation. Let's rewrite the getDescription () method:

GetDescription () {return `Full description\ n: name: ${this.name} description ${this.description} `;}

${} interpolation can be used in a pair of `- wrapped strings. It looks much more comfortable now.

Abbreviated attribute

This must be written in ES5:

Function createCoord (x, y) {return {x: X, y: y}}

ES6 can use abbreviated properties later:

Function createCoord (x, y) {return {x, y}}

Doesn't it look fresher?

Method attribute

A method property is a property that defines a property pointing to a method in an object. Consider the following ES5 code as an example:

Const math = {add: function (arecom b) {return a + b;}, sub: function (areco b) {return a-b;}, multiply: function (ameme b) {return a * b;}}

After ES6, all you have to do is write:

Const math = {return a + b;}, sub (add a + b) {return a-b;}, multiply (a * b) {return a * b;}} deconstruction assignment

Deconstructing assignment is beneficial to the mental health of developers.

Consider the following code:

Function handle (req, res) {const name = req.body.name; const description = req.body.description; const url = req.url; log ('url endpoint', url); / / A lot of code logic dbService.createPerson (name, description)}

From any point of view, the above code is not perfect, but it does reflect an application scenario in which we want to get data from different levels of objects. You might ask, what's the problem here? Well, I can save some keystrokes without declaring so many variables.

Function handle (req, res) {const {body: {name, description}, url} = req; log ('url endpoint', url); / / A large number of code logic dbService.createPerson (name, description)

Look, the code above compresses three lines into one.

Deconstructing assignment is not limited to objects. It also applies to arrays. Consider the following code:

Const array = [1, const 2, 3, 4, 5, 5, 6]; const a = array [0]; const c = array [2]

The above code can be rewritten in a more elegant way:

Const array = [1, 2, 3, 4, 5, 6]; const [a, c,... remaining] = arr;// remaining = [4, 5, 5, 6]

We can use the pattern above to match the values of the decomposed array. We use to skip some values. The remaining parameters mentioned above can also be used here, where we capture the remaining array members with the remaining parameters.

Deconstructing assignments can also be used for functions and parameters. When a function has more than 2-3 parameters, it is the de facto standard of JavaScript to use an object to collect all parameters. For example, the following function:

Function doSomething (config) {if (config.a) {.} if (config.b) {.} if (config.c) {.}}

There is a better way to write:

Function doSomething ({a, b, c}) {if (a) {...} if (b) {...} if (c) {...}} array method

ES6 introduces many useful array methods, such as:

Find (). Find the member in the list. Return null to indicate that it is not found.

FindIndex () to find the index of a list member

Some () to check whether an assertion is true on at least one member of the list

Includes, whether the list contains an item

The following code helps you understand their usage:

Const array = [{id: 1, checked: true}, {id: 2}]; arr.find (item = > item.id = 2) / / {id: 2} arr.findIndex (item = > item.id = 2) / / 1arr.some (item = > item.checked) / / trueconst numberArray = [1, 2, 3, 4]; numberArray.includes (2) / / truePromises + Async/Await

If you have been in this circle for a few years, you may remember that there was a time when we only had a callback, like this:

Function doSomething (cb) {setTimeout (() = > {cb ('done')}, 3000)} doSomething ((arg) = > {console.log (' done here', arg);})

We use callbacks because some operations are asynchronous and take time to complete. Then we had the promise library, and people started using it. Then JavaScript gradually added native support for promise.

Function doSomething () {return new Promise ((resolve, reject) = > {setTimeout () = > {resolve ('done')}, 3000)} doSomething () .then (arg = > {console.log (' done here', arg);})

We can even string the promise together like this:

GetUser () .then (getOrderByUser) .then (getOrderItemsByOrder) .then (orderItems = > {/ / process sorted members})

And then life got better, and we had async/await, and the above code could be written like this:

Async function getItems () {try {const user = await getUser (); const order = await getOrderByUser (user); const items = await getOrderItemsByOrder (order); return items;} catch (err) {/ / handles errors here. It is recommended to return a value or rethrow the error}} getItems () .then (items = > {/ / processing sorted members}) module

Almost any programming language supports the concept of modules, which divides the code into multiple files, each of which is a self-contained unit (module). Consider the following code:

/ / math.jsexport function add (return a + b) {return a + b;} export function sub (areco b) {return a-b;} export default mult (areco b) = > a * b math';mult / main.jsimport mult, {add, sub} from'. / math';mult (2,4) / / 8add (1) / / 2sub (1) / /-1

We noted above with the export keyword that the add and sub structures are publicly visible to any module that introduces the module. The export default keyword indicates the structure you get when you only import the module. In main.js, we named the imported default mult and indicated that we introduced two methods, add () and sub ().

Arrow function and dictionary scope this

I have used the arrow function in many places in this article, it is just another function representation. In the past, we could only declare a function like this:

Function printArray (arr) {/ / specific operation}

Now we can also write:

Const printArray = (arr) = > {/ / specific operation}

We can also write the function declaration on one line:

Const add = (a) b) = > a + b

The above code indicates that we perform the operation and return the result. We can also return an object using the following syntax:

Const create = (a) b) = > ({x: a, y: B})

In the past, we encountered the problem of not knowing what this is. Consider the following code:

Let array = [1Jing 2jue 3]; function sum () {this.total = 0; arr.forEach (function (item) {this.total+= item; / / Bad, `this` is the `this`}) return total; of the inner function.

The this in the above code points to the this of the forEach internal function, which is not what we want. In the past, we solved this problem in the following ways:

Function sum () {this.total = 0; var self = this; arr.forEach (function (item) {self.total+= item; / / We use `self` here, it can solve the problem, but it feels a little awkward}) return total;}

The arrow function solves the problem, no longer using self, and now the code looks like this:

Function sum () {this.total = 0; arr.forEach ((item) = > {this.total+= item; / / everything is fine, `this` points to the outer function}) return total;} that's all for "javascript feature instance analysis". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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

Internet Technology

Wechat

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

12
Report