js使用对象形式减少if判断

49 篇文章 1 订阅
5 篇文章 0 订阅

前言:项目中经常有不同字段显示不通过状态内容的需求,多数是采用if判断的形式,最好是将其写成对象的形式,既美观有可以减少判断的高频使用。

实例1:基础的一对一字段判断

//原始if形式
export function formatFood(type) {
    if (type == 'SG') {
        return '水果';
    } else if (type == 'RL') {
        return '肉类';
    } else if (type == 'SC') {
        return '蔬菜';
    } else if (type == 'GL') {
        return '谷类';
    } else {
        return '其他';
    }
}

//对象形式
export function formatYDLX(type) {
    return {
		SG: '水果',
		RL: '肉类',
		SC: '蔬菜',
        GL: '谷类'
	}[type] || '其他'
}

实例2. 数量不多的多对一判断

export function formatFood(type) {
	if (type == 'PG' || type == 'TZ' || type == 'XJ' || type == 'XG' || type == 'LZ' || type == 'TG') {
		return '水果';
	} else if (type == 'RL') {
		return '肉类';
	} else if (type == 'SC') {
		return '蔬菜';
	} else if (type == 'GL') {
		return '谷类';
	}
}

//修改后
export function formatFood(type) {
    const fruit = ['PG','TZ','XJ','XG', 'LZ', 'TG'].includes(type) ? '水果' : '';
    return {
		RL: '肉类',
		SC: '蔬菜',
		GL: '谷类'
	}[type] || fruit  
}

实例3. 数量多的多对一判断,建议单独建一个文件来放映射关系

原始形式

export function formatFood(type) {
	if (type == 'PG' || type == 'TZ' || type == 'XJ' || type == 'XG' || type == 'LZ' || type == 'TG') {
		return '水果';
	} else if (type == 'NR' || type == 'ZR' || type == 'JR' || type == 'YR' || type == 'YR' || type == 'GR') {
		return '肉类';
	} else if (type == 'NG' || type == 'DG' || type == 'SG' || type == 'QZ' || type == 'LJ' || type == 'HLB') {
		return '蔬菜';
	} else if (type == 'DL') {
		return '豆类';
	} else if (type == 'GL') {
		return '谷类';
	} else if (type == 'ML') {
		return '面类';
	} 
    ......

}

修改后:

1.建一个food-map.js文件存放映射关系;

/**
* 食物映射表
*/

export default {
    'PG,TZ,XJ,XG,LZ,TG':'水果',
    'NR,ZR,JR,YR,ER,GR':'肉类',
    'NG,DG,SG,QZ,LJ,HLB':'蔬菜',
    DL:'豆类',
    GL:'谷类',
    ML:'面类',
    ......
}

 2.在公共方法里面进行逻辑操作;

import foodEnum from '@/core/food-map.js';

export function formatZYJD(type) {
    //foodEnum为引进来的映射文件
    for (const key in foodEnum) {
        const foodKey = key.split(',')
        if (foodKey.includes(type)) {
            return foodEnum[foodKey]
        }
    }
    return '--'
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值