Table of Contents
Premise
For example
Summary
Home Web Front-end JS Tutorial Elegant way to write complex judgments in JavaScript

Elegant way to write complex judgments in JavaScript

Jun 16, 2020 pm 04:54 PM
javascript front end WeChat regular expression

Elegant way to write complex judgments in JavaScript

Premise

We often encounter complex logical judgments when writing js code. Usually you can use if/else or switch to implement multiple conditional judgments, but There will be a problem with this. As the logic complexity increases, 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? This article will give you a try one time.

For example

Look at a piece of code first

/**
 * 按钮点击事件
 * @param {number} status 活动状态:1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消
 */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')
  }
}复制代码
Copy after login

You can see the click logic of this button through the code: do two things according to different activity states, send logs to bury points and jump to the corresponding page. You can easily propose a rewriting plan for this code. The switch appears:

/**
 * 按钮点击事件
 * @param {number} status 活动状态:1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消
 */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
  }
}复制代码
Copy after login

Well, this looks much clearer than if/else. Careful students also discovered the small Tip, when the logic of case 2 and case 3 is the same, you can omit the execution statement and break, and the logic of case 3 will be automatically executed in case 2.

At this time, some students will say that there is a simpler way to write:

const actions = {  '1': ['processing','IndexPage'],  '2': ['fail','FailPage'],  '3': ['fail','FailPage'],  '4': ['success','SuccessPage'],  '5': ['cancel','CancelPage'],  'default': ['other','Index'],
}/**
 * 按钮点击事件
 * @param {number} status 活动状态:1开团进行中 2开团失败 3 商品售罄 4 开团成功 5 系统取消
 */const onButtonClick = (status)=>{  let action = actions[status] || actions['default'],
      logName = action[0],
      pageName = action[1]
  sendLog(logName)
  jumpTo(pageName)
}复制代码
Copy after login

The above code does look cleaner. The smart thing about this method is that it takes the judgment condition as an object The attribute name uses the processing logic as the attribute value of the object. When the button is clicked, logical judgment is made by searching the object attributes. This writing method is particularly suitable for unary conditional judgment.

Is there any other way to write it? Some:

const actions = new Map([
  [1, ['processing','IndexPage']],
  [2, ['fail','FailPage']],
  [3, ['fail','FailPage']],
  [4, ['success','SuccessPage']],
  [5, ['cancel','CancelPage']],
  ['default', ['other','Index']]
])/**
 * 按钮点击事件
 * @param {number} status 活动状态:1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消
 */const onButtonClick = (status)=>{  let action = actions.get(status) || actions.get('default')
  sendLog(action[0])
  jumpTo(action[1])
}复制代码
Copy after login

Writing like this uses the Map object in es6. Isn’t it more fun? What is the difference between Map object and Object object?

  1. An object usually has its own prototype, so an object always has a "prototype" key.
  2. The key of an object can only be a string or Symbols, but the key of a Map can be any value.
  3. You can easily get the number of key-value pairs of a Map through the size attribute, while the number of key-value pairs of an object can only be confirmed manually.

We need to upgrade the problem. In the past, we only needed to judge the status when clicking the button. Now we also need to judge the user’s identity:

/**
 * 按钮点击事件
 * @param {number} status 活动状态:1开团进行中 2开团失败 3 开团成功 4 商品售罄 5 有库存未开团
 * @param {string} identity 身份标识:guest客态 master主态
 */const onButtonClick = (status,identity)=>{  if(identity == 'guest'){    if(status == 1){      //do sth
    }else if(status == 2){      //do sth
    }else if(status == 3){      //do sth
    }else if(status == 4){      //do sth
    }else if(status == 5){      //do sth
    }else {      //do sth
    }
  }else if(identity == 'master') {    if(status == 1){      //do sth
    }else if(status == 2){      //do sth
    }else if(status == 3){      //do sth
    }else if(status == 4){      //do sth
    }else if(status == 5){      //do sth
    }else {      //do sth
    }
  }
}复制代码
Copy after login

Forgive me for not writing the specific details of each judgment. Logic, because the code is too verbose.

Forgive me for using if/else again, because I see many people still using if/else to write such large sections of logical judgment.

We can see from the above example that when your logic is upgraded to binary judgment, your judgment amount will double, and your code amount will also double. How to write more refreshingly at this time?

const actions = new Map([
  ['guest_1', ()=>{/*do sth*/}],
  ['guest_2', ()=>{/*do sth*/}],
  ['guest_3', ()=>{/*do sth*/}],
  ['guest_4', ()=>{/*do sth*/}],
  ['guest_5', ()=>{/*do sth*/}],
  ['master_1', ()=>{/*do sth*/}],
  ['master_2', ()=>{/*do sth*/}],
  ['master_3', ()=>{/*do sth*/}],
  ['master_4', ()=>{/*do sth*/}],
  ['master_5', ()=>{/*do sth*/}],
  ['default', ()=>{/*do sth*/}],
])/**
 * 按钮点击事件
 * @param {string} identity 身份标识:guest客态 master主态
 * @param {number} status 活动状态:1 开团进行中 2 开团失败 3 开团成功 4 商品售罄 5 有库存未开团
 */const onButtonClick = (identity,status)=>{  let action = actions.get(`${identity}_${status}`) || actions.get('default')
  action.call(this)
}复制代码
Copy after login

The core logic of the above code is: splice the two conditions into a string, and search and execute the Map object using the conditional string as the key and the processing function as the value. This writing method is used in multiple It is especially useful when making conditional judgments.

Of course, the above code is similar if it is implemented using Object objects:

const actions = {  'guest_1':()=>{/*do sth*/},  'guest_2':()=>{/*do sth*/},  //....}const onButtonClick = (identity,status)=>{  let action = actions[`${identity}_${status}`] || actions['default']
  action.call(this)
}复制代码
Copy after login

If some students feel that it is a bit awkward to spell the query conditions into strings, then there is another solution, which is to use Map objects. , using the Object object as the key:

const actions = new Map([
  [{identity:'guest',status:1},()=>{/*do sth*/}],
  [{identity:'guest',status:2},()=>{/*do sth*/}],  //...])const onButtonClick = (identity,status)=>{  let action = [...actions].filter(([key,value])=>(key.identity == identity && key.status == status))
  action.forEach(([key,value])=>value.call(this))
}复制代码
Copy after login

Is it a little more advanced?

The difference between Map and Object can also be seen here. Map can use any type of data as key.

Now we will upgrade the difficulty a little bit. What if the processing logic of status1-4 is the same in the guest case. The worst case is this:

const actions = new Map([
  [{identity:'guest',status:1},()=>{/* functionA */}],
  [{identity:'guest',status:2},()=>{/* functionA */}],
  [{identity:'guest',status:3},()=>{/* functionA */}],
  [{identity:'guest',status:4},()=>{/* functionA */}],
  [{identity:'guest',status:5},()=>{/* functionB */}],  //...])复制代码
Copy after login

A better way to write it is Cache the processing logic function:

const actions = ()=>{  const functionA = ()=>{/*do sth*/}  const functionB = ()=>{/*do sth*/}  return new Map([
    [{identity:'guest',status:1},functionA],
    [{identity:'guest',status:2},functionA],
    [{identity:'guest',status:3},functionA],
    [{identity:'guest',status:4},functionA],
    [{identity:'guest',status:5},functionB],    //...
  ])
}const onButtonClick = (identity,status)=>{  let action = [...actions()].filter(([key,value])=>(key.identity == identity && key.status == status))
  action.forEach(([key,value])=>value.call(this))
}复制代码
Copy after login

Writing like this can already meet daily needs, but to be serious, it is still a bit uncomfortable to rewrite functionA 4 times above. If the judgment condition becomes particularly complicated, for example, identity has There are 3 states, and status has 10 states. Then you need to define 30 processing logics, and often many of these logics are the same. This seems to be something I don’t want to accept. It can be implemented like this:

const actions = ()=>{  const functionA = ()=>{/*do sth*/}  const functionB = ()=>{/*do sth*/}  return new Map([
    [/^guest_[1-4]$/,functionA],
    [/^guest_5$/,functionB],    //...
  ])
}const onButtonClick = (identity,status)=>{  let action = [...actions()].filter(([key,value])=>(key.test(`${identity}_${status}`)))
  action.forEach(([key,value])=>value.call(this))
}复制代码
Copy after login

The advantages of Map are more prominent here. Regular types can be used as keys, which opens up unlimited possibilities. If the demand changes, a log burying point must be sent for all guest situations, and different status situations also require separate logical processing, then we You can write it like this:

const actions = ()=>{  const functionA = ()=>{/*do sth*/}  const functionB = ()=>{/*do sth*/}  const functionC = ()=>{/*send log*/}  return new Map([
    [/^guest_[1-4]$/,functionA],
    [/^guest_5$/,functionB],
    [/^guest_.*$/,functionC],    //...
  ])
}const onButtonClick = (identity,status)=>{  let action = [...actions()].filter(([key,value])=>(key.test(`${identity}_${status}`)))
  action.forEach(([key,value])=>value.call(this))
}复制代码
Copy after login

That is to say, using the characteristics of array loops, logic that meets the regular conditions will be executed. Then you can execute public logic and individual logic at the same time. Because of the existence of regular rules, you can open up your imagination. To unlock more ways to play, I won’t go into details in this article.

Summary

This article has taught you 8 ways to write logical judgments, including:

  1. if/else
  2. switch
  3. When making one-yuan judgment: Save it in Object
  4. When making one-way judgment: Save it in Map
  5. When making multiple judgments: Splice the condition into a string and save it in Object
  6. Multiple When judging: Splice the condition into a string and save it in the Map
  7. When judging multiple variables: Save the condition as an Object and save it in the Map
  8. When judging multiple variables: Write the condition as a regular expression and save it in the Map

At this point, this article will come to an end. I hope your future life will not only have if/else/switch.

If you are interested in this article, please follow the author's WeChat public account: "大 Zhuan Zhuan Fe"

Recommended tutorial: "JavaScriptBasic Tutorial

The above is the detailed content of Elegant way to write complex judgments in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

There are rumors that 'iPhone 16 may not support WeChat', and Apple's technical consultant in China said that it is communicating with Tencent about app store commissions There are rumors that 'iPhone 16 may not support WeChat', and Apple's technical consultant in China said that it is communicating with Tencent about app store commissions Sep 02, 2024 pm 10:45 PM

Thanks to netizens Qing Qiechensi, HH_KK, Satomi Ishihara and Wu Yanzu of South China for submitting clues! According to news on September 2, there are recent rumors that "iPhone 16 may not support WeChat." In response to this, a reporter from Shell Finance called Apple's official hotline. Apple's technical consultant in China responded that whether iOS systems or Apple devices can continue to use WeChat, and WeChat The issue of whether it can continue to be listed and downloaded on the Apple App Store requires communication and discussion between Apple and Tencent to determine the future situation. Software App Store and WeChat Problem Description Software App Store technical consultant pointed out that developers may need to pay fees to put software on the Apple Store. After reaching a certain number of downloads, Apple will need to pay corresponding fees for subsequent downloads. Apple is actively communicating with Tencent,

deepseek image generation tutorial deepseek image generation tutorial Feb 19, 2025 pm 04:15 PM

DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI ​​Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

People familiar with the matter responded that 'WeChat may not support Apple iPhone 16': Rumors are rumors People familiar with the matter responded that 'WeChat may not support Apple iPhone 16': Rumors are rumors Sep 02, 2024 pm 10:43 PM

Rumors of WeChat supporting iPhone 16 were debunked. Thanks to netizens Xi Chuang Jiu Shi and HH_KK for submitting clues! According to news on September 2, there are rumors today that WeChat may not support iPhone 16. Once the iPhone is upgraded to the iOS 18.2 system, it will not be able to use WeChat. According to "Daily Economic News", it was learned from people familiar with the matter that this rumor is a rumor. Apple's response: According to Shell Finance, Apple's technical consultant in China responded that the issue of whether WeChat can continue to be used on iOS systems or Apple devices, and whether WeChat can continue to be listed and downloaded in the Apple App Store, needs to be resolved between Apple and Tencent. Only through communication and discussion can we determine the future situation. Currently, Apple is actively communicating with Tencent to confirm whether Tencent will continue to

gateio Chinese official website gate.io trading platform website gateio Chinese official website gate.io trading platform website Feb 21, 2025 pm 03:06 PM

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

List of handling fees for okx trading platform List of handling fees for okx trading platform Feb 15, 2025 pm 03:09 PM

The OKX trading platform offers a variety of rates, including transaction fees, withdrawal fees and financing fees. For spot transactions, transaction fees vary according to transaction volume and VIP level, and adopt the "market maker model", that is, the market charges a lower handling fee for each transaction. In addition, OKX also offers a variety of futures contracts, including currency standard contracts, USDT contracts and delivery contracts, and the fee structure of each contract is also different.

gateio exchange app old version gateio exchange app old version download channel gateio exchange app old version gateio exchange app old version download channel Mar 04, 2025 pm 11:36 PM

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Mar 04, 2025 pm 04:51 PM

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

See all articles