In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to write elegant JavaScript code". In daily operation, I believe many people have doubts about how to write elegant JavaScript code. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "how to write elegant JavaScript code". Next, please follow the editor to study!
Variable
1. Variable naming
Generally speaking, when we define variables, we need to use meaningful vocabulary commands to know the meaning of each other.
/ / bad code const yyyymmdstr = moment () .format ('YYYY/MM/DD'); / / better code const currentDate = moment () .format (' YYYY/MM/DD')
2. Can be described
A new variable is generated from a variable, and you also need to name the new variable, which means that each variable knows what it does the first time you see it.
/ / bad code const ADDRESS = 'One Infinite Loop, Cupertino 95014; const CITY_ZIP_CODE_REGEX = / ^ [^,\] + [,\\ s] + (. +?)\ s * (\ d {5})? $/; saveCityZipCode (ADDRESS.match (CITY_ZIP_CODE_REGEX) [1], ADDRESS.match (CITY_ZIP_CODE_REGEX) [2]); / / better code const ADDRESS =' One Infinite Loop, Cupertino 95014' Const CITY_ZIP_CODE_REGEX = / ^ [^,\] + [,\\ s] + (. +?)\ s * (\ d {5})? $/; const [, city, zipCode] = ADDRESS.match (CITY_ZIP_CODE_REGEX) | | []; saveCityZipCode (city, zipCode)
3. Naming of formal parameters
In the loop of for, forEach, map, we have to name directly.
/ / bad code const locations = ['Austin',' New York', 'San Francisco']; locations.map ((l) = > {doStuff (); doSomeOtherStuff (); / /. / / you need to see other code to determine what' l' is for. Dispatch (l);}); / / better code const locations = ['Austin',' New York', 'San Francisco']; locations.forEach ((location) = > {doStuff (); doSomeOtherStuff (); / /. Dispatch (location);})
4. Avoid meaningless prefixes
For example, if we only create one object, there is no need to add the object name to the properties of each object.
/ / bad code const car = {carMake: 'Honda', carModel:' Accord', carColor: 'Blue'}; function paintCar (car) {car.carColor =' Red';} / / better code const car = {make: 'Honda', model:' Accord', color: 'Blue'}; function paintCar (car) {car.color =' Red';}
5. Default value
/ / bad code function createMicrobrewery (name) {const breweryName = name | | 'Hipster Brew Co.'; / /...} / / better code function createMicrobrewery (name =' Hipster Brew Co.') {/ /..} function
1. Parameters
If there are many parameters, you should use the deconstruction method of ES6 to transfer parameters.
/ bad code function createMenu (title, body, buttonText, cancellable) {/ /...} / / better code function createMenu ({title, body, buttonText, cancellable}) {/ /...} / / better code createMenu ({title: 'Foo', body:' Bar', buttonText: 'Baz', cancellable: true})
2. Unitary treatment
It is best to do only one thing in a method, not to deal with too much, so that the readability of the code is very high.
/ / bad code function emailClients (clients) {clients.forEach ((client) = > {const clientRecord = database.lookup (client); if (clientRecord.isActive ()) {email (client);}});} / / better code function emailActiveClients (clients) {clients .filter (isActiveClient) .forEach (email);} function isActiveClient (client) {const clientRecord = database.lookup (client); return clientRecord.isActive ();}
3. Object sets default properties
/ / bad code const menuConfig = {title: null, body: 'Bar', buttonText: null, cancellable: true}; function createMenu (config) {config.title = config.title | |' Foo'; config.body = config.body | | 'Bar'; config.buttonText = config.buttonText | |' Baz'; config.cancellable = config.cancellable! = undefined? Config.cancellable: true;} createMenu (menuConfig); / / better code const menuConfig = {title: 'Order', / /' body' key missing buttonText: 'Send', cancellable: true}
4. Avoid side effects
The function receives a value and returns a new value, and other behaviors are called side effects, such as modifying global variables, IO files, and so on.
When functions do require side effects, such as IO files, do not use multiple functions / classes for file operations, but only one function / class. In other words, side effects need to be dealt with in the only place.
There are three major sinkholes for side effects: changing variable data types at will, sharing states without data structures at will, and not dealing with side effects in the same place.
/ / bad code / / the global variable is referenced by a function / / now this variable has changed from a string to an array, and if there are other function references, an unforeseen error will occur. Var name = 'Ryan McDermott'; function splitIntoFirstAndLastName () {name = name.split ('');} splitIntoFirstAndLastName (); console.log (name); / / ['Ryan',' McDermott']; / / better code var name = 'Ryan McDermott'; var newName = splitIntoFirstAndLastName (name) function splitIntoFirstAndLastName (name) {return name.split (');} console.log (name); / / 'Ryan McDermott'; console.log (newName) / / ['Ryan',' McDermott']
In JavaScript, basic types are passed by assignment, and objects and arrays are passed by reference. Take reference delivery as an example:
Suppose we write a shopping cart, add items to the shopping cart through the addItemToCart () method, and modify the shopping cart array. At this point, the purchase () method is called to purchase, and because the reference is passed, the shopping cart array obtained happens to be the latest data.
It looks fine. Is that right?
If the network fails when the user clicks to buy, the purchase () method is called repeatedly, and at the same time the user adds a new item, and the network is restored. Then it is wrong for the purchase () method to get the shopping cart array.
To avoid this problem, we need to clone the shopping cart array and return the new array each time we add a new item.
/ / bad code const addItemToCart = (cart, item) = > {cart.push ({item, date: Date.now ()});}; / / better code const addItemToCart = (cart, item) = > {return [... cart, {item, date: Date.now ()}]}
5. Global method
In JavaScript, never pollute the overall situation, it will produce unpredictable bug in the production environment. For example, let's say you add a diff method to Array.prototype to determine the difference between two arrays. Your colleague plans to do something similar, but his diff method is used to determine the difference between the first elements of two arrays. It is obvious that there will be conflicts in your methods. If we encounter such problems, we can use the syntax of ES2015/ES6 to extend Array.
/ bad code Array.prototype.diff = function diff (comparisonArray) {const hash = new Set (comparisonArray); return this.filter (elem = >! hash.has (elem));}; / / better code class SuperArray extends Array {diff (comparisonArray) {const hash = new Set (comparisonArray); return this.filter (elem = >! hash.has (elem));}}
6. Avoid type checking
JavaScript is untyped, which means that you can pass any type of parameter. This degree of freedom is easily disturbing, and you will check the type unconsciously. Think about it, do you really need to check the type or is there something wrong with your API design?
/ / bad code function travelToTexas (vehicle) {if (vehicle instanceof Bicycle) {vehicle.pedal (this.currentLocation, new Location ('texas'));} else if (vehicle instanceof Car) {vehicle.drive (this.currentLocation, new Location (' texas'));}} / better code function travelToTexas (vehicle) {vehicle.move (this.currentLocation, new Location ('texas');}
If you need to do static type checking, such as strings, integers, etc., it is recommended to use TypeScript, otherwise your code will become smelly and long.
/ / bad code function combine (val1, val2) {if (typeof val1 = = 'number' & & typeof val2 =' number' | | typeof val1 = 'string' & & typeof val2 =' string') {return val1 + val2;} throw new Error ('Must be of type String or Number');} / better code function combine (val1, val2) {return val1 + val2;} complex condition judgment
When we write js code, we often encounter complex logic judgments. Usually we can use if/else or switch to achieve multiple conditional judgments, but there will be a problem. With the increase of logic complexity, the if/else/switch in the code will become more and more bloated and difficult to understand, so how to write judgment logic more elegantly
1 、 if/else
Click the list button event
/ * Button Click event * @ param {number} status activity status: 1 in the opening process, 2 failed in the opening process, 3 sold out, 4 opened successfully, 5 the system canceled * / const onButtonClick = (status) = > {if (status = = 1) {sendLog ('processing') jumpTo (' IndexPage')} else if (status = = 2) {sendLog ('fail') jumpTo (' FailPage')} else if ( Status = = 3) {sendLog ('fail') jumpTo (' FailPage')} else if (status = = 4) {sendLog ('success') jumpTo (' SuccessPage')} else if (status = = 5) {sendLog ('cancel') jumpTo (' CancelPage')} else {sendLog ('other') jumpTo (' Index')}}
What we can see from the above is to do different things through different states. The code looks very ugly. You can easily propose a rewriting plan for this code. Switch appears:
2 、 switch/case
/ * Button Click event * @ param {number} status activity status: 1 in the opening process 2 failed in the opening process, 3 goods sold out 4 opened successfully 5 system canceled * / const onButtonClick = (status) = > {switch (status) {case 1: sendLog ('processing') jumpTo (' IndexPage') break case 2: case 3: sendLog ('fail') jumpTo ( 'FailPage') break case 4: sendLog (' success') jumpTo ('SuccessPage') break case 5: sendLog (' cancel') jumpTo ('CancelPage') break default: sendLog (' other') jumpTo ('Index') break}}
This looks much clearer than if/else, careful students also found tips, case 2 and case 3 logic is the same, you can omit the execution of statements and break, then case 2 case automatically executes the logic of case 3.
3. Deposit to Object
The judgment condition is regarded as the attribute name of the object, and the processing logic is regarded as the attribute value of the object. When the button is clicked, the logical judgment is made through the way of finding the object attribute. This writing method is especially suitable for the case of unitary condition judgment.
Const actions = {'1percent: [' processing','IndexPage'], '2percent: [' fail','FailPage'], '3percent: [' fail','FailPage'], '4percent: [' success','SuccessPage'], '5percent: [' cancel','CancelPage'], 'default': [' other','Index'] } / * Button Click event * @ param {number} status activity status: 1 in the opening process, 2 failed in the opening process, 3 goods sold out, 4 opened successfully, 5 system canceled * / const onButtonClick = (status) = > {let action = actions [status] | | actions ['default'], logName = action [0], pageName = action [1] sendLog (logName) jumpTo (pageName)}
4. Deposit to Map
Const actions = new Map ([[1, ['processing','IndexPage']], [2, [' fail','FailPage']], [3, ['fail','FailPage']], [4, [' success','SuccessPage']], [5, ['cancel','CancelPage']], [' default', ['other']) ('Index']) / * * Button Click event * @ param {number} status activity status: 1 in the opening process, 2 failed in the opening process, 3 sold out, 4 sold out successfully, 5 system canceled * / const onButtonClick = (status) = > {let action = actions.get (status) | actions.get (' default') sendLog (action [0]) jumpTo (action [1])}
Isn't it better to use the Map object in es6? what's the difference between a Map object and an Object object?
An object usually has its own prototype, so an object always has a "prototype" key.
The key of an object can only be a string or Symbols, but the key of an Map can be any value.
You can easily get the number of key-value pairs of a Map through the size property, while the number of key-value pairs of objects can only be confirmed manually.
Code style
Constant capitalization
/ / bad code const DAYS_IN_WEEK = 7; const daysInMonth = 30; const songs = ['Back In Black',' Stairway to Heaven', 'Hey Jude']; const Artists = [' ACDC', 'Led Zeppelin',' The Beatles']; function eraseDatabase () {} function restore_database () {} class animal {} class Alpaca {} / / better code const DAYS_IN_WEEK = 7; const DAYS_IN_MONTH = 30 Const SONGS = ['Back In Black',' Stairway to Heaven', 'Hey Jude']; const ARTISTS = [' ACDC', 'Led Zeppelin',' The Beatles']; function eraseDatabase () {} function restoreDatabase () {} class Animal {} class Alpaca {}
Declare first and then call
/ / bad code class PerformanceReview {constructor (employee) {this.employee = employee;} lookupPeers () {return db.lookup (this.employee, 'peers');} lookupManager () {return db.lookup (this.employee,' manager');} getPeerReviews () {const peers = this.lookupPeers (); / /...} perfReview () {this.getPeerReviews (); this.getManagerReview () This.getSelfReview ();} getManagerReview () {const manager = this.lookupManager ();} getSelfReview () {/...}} const review = new PerformanceReview (employee); review.perfReview (); / / better code class PerformanceReview {constructor (employee) {this.employee = employee;} perfReview () {this.getPeerReviews (); this.getManagerReview (); this.getSelfReview () } getPeerReviews () {const peers = this.lookupPeers (); / /...} lookupPeers () {return db.lookup (this.employee, 'peers');} getManagerReview () {const manager = this.lookupManager ();} lookupManager () {return db.lookup (this.employee,' manager') } getSelfReview () {/...}} const review = new PerformanceReview (employee); review.perfReview (); at this point, the study on "how to write elegant and attractive JavaScript code" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.