preface

  • In the day-to-day business development process, can’t avoid will have the same value or multiple values judgment to display or perform other logic code, we can choose different judgments for different statement to write the corresponding logic, but how to choose to use which a judgment or other written statements can make the code more elegant and more readable?

There are only two possibilities

  • When the judgment is either/or (and there are only two possibilities), we tend to chooseif elseThis judgment statement.
// if else
if(name === 'detanx') { ... }
else { ... }
Copy the code

Three yuan

  • In fact, when there is a single statement, assignment, etc., we can also choose the ternary operation statement.
// let isMaster = false; isMaster = name === 'detanx' ? true : false;Copy the code
  • After the above ternary statement rewriting, the number of code is reduced, relatively more elegant, more readable thanif elseAlmost.
  • It is not recommended to nest ternary operations when using ternary statements. Such as:
let masterStatus = 0; // 0 super, 1 master, 2 normal let master = 'detanx'; masterStatus = master === 'detanx' ? 0 : (master === '17' ? 1, 2);Copy the code

||&&

  • In addition to ternary, we can use it in certain cases||,&&Operator. For example, requesting data results:
// || let responseData = []; request(res => { if(res.code === 200) { responseData = res.data || []; // res.data exists, and the backend convention null/Array}}) responseData && responseData.map(item => {// determine the responseData // item... })Copy the code

??

  • If and only if the left-hand side of the operator isnullundefined, select the value on the right.
let name = '';
const isNullOrUndefined = null;
name = isNullOrUndefined ?? 'default';
Copy the code

A variety of possible

  • When you think of multiple possibilities, the first thing that comes to mind is probablyif... else if... elseorswitch... case. For example, judging different events:
  1. Multiple possibilities correspond to the same situation
If (status = = = 0 | | status = = = 1 | | status = = = 2 | | status = = = 3) {the console. The log (' button you can click on the '); } / / = > if ([0, 1, 2, 3]. Includes (status)) {the console. The log (' button you can click on the '); }Copy the code
  1. There are multiple possibilities for different situations
  • Different events require different behavior and execution logic.
let content = [];
if(event === 'click') {
    content = ['jump', clickFunction];
} else if (event === 'blur') {
    content = ['jungle', blurFunction];
} else if (event === 'scroll') {
    content = ['scroll', scrollFunction];
} else if (event === 'size') {
    content = ['change', sizeFunction];
} else if (event === 'focus') {
    content = ['jungle', focusFunction];
} else {
    content = ['other', otherFunction];
}
Copy the code
  • Rewrite the above code using object data structures.
let content = [];
const eventObject = {
    'click': ['jump', clickFunction],
    'blur': ['jungle', blurFunction],
    'scroll': ['scroll', scrollFunction],
    'size': ['change', sizeFunction],
    'focus': ['jungle', focusFunction],
}
content = eventObject[event] || ['other', otherFunction];
Copy the code
  • According to the actual situation of our business, we can also flexibly replace other data structures. Many businesses need to display different documents according to a certain value. For example, by determining state values (status) displays the current course status.
// status 0 deleted 1 unstarted 2 unstarted 3 unfinished 4 evaluated let text = '';Copy the code
  • if... else
If (status === 0) {text = 'deleted'} else if(status === 1) {text = 'not started'} else if(status === 2) {text = 'in class'} else If (status === 3) {text = '--'} else if (status === 4) {text = '--'}Copy the code
  • switch... case
Switch (status) {case 0: text = 'delete '; break; Case 1: text = 'not started '; break; Case 2: text = 'c '; break; Case 3: text = 'background-color '; break; Case 4: text = 'append '; break; default: text = '--'; break; }Copy the code
  • There are two ways to write it, the readability is good, but it is very redundant, is there a more concise way to write? Look down:
Const statusTextArray = [' Deleted ', 'not started ',' in class ', 'dismissed ',' evaluated ']; text = statusTextArray[status] || '--';Copy the code
  • In two lines of code, it’s a lot simpler (in the case of non-continuous values, we just need to set the subscript to null or undefined, if the value is too large, it’s not recommended to use the above method). This is how we use the nature of arrays and the nature of our data. One would say, well, what if you only apply to numbers, not numbers or numbers that are too large? Don’t worry, read on:
// status non-value or too large const statusTextObject = {100: 'deleted ', 101:' not started ', 102: 'in class ', 103:' out of class ', 104: 'has assessed'} text = statusTextObject [status] | | '--'; // Replace the key of the object with the value of status.Copy the code
  1. Multiple values correspond to multiple cases
  • In the course of daily development, we may need to do display or other logical operations by judging more than one value. We may need to judge2An even2Student: more than 2, does that mean you have to writeif... else?
If (limit === 'super') {if(status === 0) {// do... } else if (status === 1) { // do ... } else if (status === 2) { // do ... } else if (status === 3) { // do ... } else if (status === 4) { // do ... } } else if (limit === 'normal') { if(status === 0) { // do ... } else if (status === 1) { // do ... } else if (status === 2) { // do ... } else if (status === 3) { // do ... } else if (status === 4) { // do ... } } else { // do ... }Copy the code
  • When there are too many cases, the nesting gets deeper and deeper, and the code gets less elegant and readable.
// Overwrite const limitStatusObject = {'super-0': () => {// do... }, 'super-1': () => { // do ... } / /... 'normal-0': () => { // do ... }, 'normal-1': () => { // do ... } / /... } const limitStatusObject = {'super-0': super0Function, 'super-1': super1Function, //... 'normal-0': normal0Function, 'normal-1': normal1Function, // ... } limitStatusObject[`${limit}-${status}`].call(this);Copy the code
  • Out of the useObjectBesides, we can also useES6In theMapData structure that combines the keys of corresponding values into objects.
const limitStatusMap = new Map([ [{limit: 'super',status: 0},()=>{ // do ... }], [{limit: 'super',status: 1},()=>{ // do ... }], // ... [{limit: 'normal',status: 0},()=>{ // do ... }], [{limit: 'normal',status: 1},()=>{ // do ... }], // ... ] ); const list = [...limitStatusMap].filter(([key,value]) => (key.limit === limit && key.status === status)); list.forEach(([key,value]) => value.call(this));Copy the code
  • When several state value operations are the same under the same permission, what should we write?
const functionA = () => { // do ... } const functionB = ()=> { // do ... } const limitStatusMap = new Map([ [/^limit_[1-4]$/,functionA], [/^limit_5$/,functionB], //... ] ) const list = [...actions].filter(([key,value]) => (key.test(`${limit}_${status}`))) list.forEach(([key,value]) => value.call(this))Copy the code
  • You can use regular expressions to match the state values of the same operation.

Deep nested objects

  • Encountered during the development process, an unavoidable deep object value, since it is deep object, then we definitely need a layer to judge whether there is a corresponding key can continue to get the next layer, otherwise, if one data of one layer is not for the object or the corresponding value does not exist, nor do the exception handling, that our program will collapse. Show the environment appears this kind of problem, affirmation is big accident, that you may be about to be fired 🦑. So how do we avoid this problem and write elegant code?
  1. Normal writing
const user = { base: { family: { parent: { mather: { name: '... ' }, father: { name: '... ' } } } } } let fatherName = ''; if(user && user.base && user.base.family && user.base.family.parent && user.base.family.parent.father) { fatherName = user.base.family.parent.father.name || '-'; }Copy the code
  • As shown above, when the object hierarchy is too deep and we need to judge at each level, what else can we write?
// Use the new ES6 features? . let fatherName = ''; fatherName = user? .base? .family? .parent? .father? .name;Copy the code

The application case

  • In project development, we may encountertabSelect lists according to differenttabIn this case, it is not possible to write a separate function for each request.
  • tipstabThere are many items3Or more,tabItem has multiple arguments that share the same value, resulting in similar processing.
// let active = 0; // Now displays TAB 0-4 const comment = [allList, homeworkList, noticeList, newCommentList, spokenList]; getShowList(active); Const comment = [undefined, homeworkList, noticeList, newCommentList, spokenList]; // In general, all tabs have different parameters, so we handle const comment = [undefined, homeworkList, noticeList, newCommentList, spokenList]; if(active === 0) { getAllList(); } getShowList(active); cosnt getAllList = () => { // request ... } cosnt getShowList = () => { // request ... }Copy the code
  • By using an array, we can eliminate the code implementation of multiple request methods. The code is reusable but slightly less readable, so we’d better add comments.

Refer to the link

  • A more elegant way to write complex JavaScript judgments

Past wonderful

  • Build from 0 Vite + Vue3 + element-plus + VUE-Router + ESLint + husky + Lint-staged
  • “Front-end advanced” JavaScript handwriting methods/use tips self-check
  • An introduction to JavaScript design patterns and creative patterns
  • Public account open small program best solution (Vue)
  • Axios you probably don’t know how to use

“Likes, favorites and comments”

❤️ follow + like + favorites + comments + forward ❤️, creation is not easy, encourage the author to create a better article, thank 🙏 everyone.