JavaScript 中的多个条件

165 阅读1分钟

img

如何处理 if 语句中的多个条件? 你用&&和||来处理吗? 这些都是检查条件是否为真的非常有用的运算符。 然而,生活并不是那么容易的,当你遇到像下面这样更长时间的情况时,你会怎么想?

if(type === 'normal' && member.type === 'vip') || (type === 'not normal' && member.type === 'eco') {...} 

如果在一个 if 语句中有很多更复杂的条件呢?

你要保持这样吗?

让我介绍检查的替代方法。

步骤 1. — 避免人为错误

//models.js
export const MEMBER_TYPE = {
  ECO = 'eco',
  VIP = 'VIP',
  {...},
}

export const TYPE = {
  NORMAL = 'normal',
  NOT_NORMAL = 'not normal',
}

步骤 2. — 声明一个数组

//implementation.js
import {MEMBER_TYPE, TYPE} from 'models.js'

const conditions = [
  condition === TYPE.NORMAL && mem_type === MEMBER_TYPE.VIP,
  condition === TYPE.NOT_NORMAL && mem_type === MEMBER_TYPE.ECO,
  {...}
];

//if you want the condition to be `or`
conditions.includes(true);
//if you want the condition to be `and`
!conditions.includes(false);

步骤 3. — 让它更实用

//implementation.js
import {MEMBER_TYPE, TYPE} from 'models.js'

function isORCondition (condition, mem_type){
    const conditions = [
      condition === TYPE.NORMAL && mem_type === MEMBER_TYPE.VIP,
      condition === TYPE.NOT_NORMAL && mem_type === MEMBER_TYPE.ECO,
      {...}
    ];
	return conditions.includes(true);
}

{...}

if(isORCondition('normal', 'vip')){...}