【前端三分钟】优化条件判断语句,让你的 if-else 更健康

本文进一步介绍判断语句的优化方法,包括if - else、switch、对象+一元条件运算符和ES6的Map。分析了各方法特点,如Map与Object的区别,还介绍了用Map处理多元条件判断及将处理逻辑缓存的优化方式,指出每种方式都有适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在之前的文章中曾经介绍过ES6的Map,并给出如何使用Map替换if-else语句的,但那篇文章中只是简单介绍。这篇文章会对判断语句的优化进行进一步的介绍。

if-else

let status = 0;

if(status === 1) {
    //todo
}else if(status === 2) {
    //todo
}else if(status === 3) {
    //todo
}
...
else {
    //todo
}

这个例子中,有多个if-else分支用来判断多种status的取值情况。

接着使用switch对上面代码进行改造:

switch

let status = 0;
switch (status) {
    case 1:
        //todo
    break;
    case 2:
        //todo
    break;
    case 3:
        //todo
    break;
    ...
    default:
        //todo
    break;
}

可以发现,当需要判断的情况多了,if-elseswitch差别并不大。尽管switch在语句上更清晰了一些。

OK,我们继续优化:使用对象+一元条件运算符的方式:

对象+ 一元条件运算符

let status = 1;
const todoList = {
    '1': ['todo'],
    '2': ['todo'],
    '3': ['todo'],
    ...
    'default': ['todo']
}
let todo = todoList[status] || todoList['default'];
//todo

这种方法将判断条件作为对象的属性名,将处理逻辑作为对象的属性值,通过对象属性名查找的方式进行逻辑处理。

但是,别停,还有其他方法:

Map

let status = 1;
const todoList = new Map([
    [1,['todo']],
    [2,['todo']],
    [3,['todo']],
    ['default',['todo']]
])
let todo = todoList.get(status) || todoList['default'];
//todo

这里使用到ES6的Map对象,使用键值对的方式进行条件匹配。但是,有人可能会问Map对象和前一个的Object对象有什么区别呢?

  • 一个Object通常都有自己的原型,即’prototype’
  • 一个Object的键只能是字符串Symnols,但一个Map的键可以是任意值。
  • Map的键值对个数可以通过Map.prototype.size得到,而对象的键值对个数只能通过手动确认。

为了更加明显的突出Map的作用,我们再来看一个例子:

进一步介绍Map

let status = 0;
let color = 'blue';

if(color === 'blue') {
    if(status === 1) {
        //todo
    }else if(status === 2) {
        //todo
    }else if(status === 3) {
        //todo
    }else {
        //todo
    }
}else if(color === 'yellow') {
    if(status === 1) {
        //todo
    }else if(status === 2) {
        //todo
    }else if(status === 3) {
        //todo
    }else {
        //todo
    }
}

这是一个二元判断,此时判断量就是加倍,代码也加倍。那么我们用Map来改造下:

let status = 0;
let color = 'blue';
const todoList = new Map([
    ['bule_1', ()=>{
        //todo
    }],
    ['blue_2', ()=>{
        //todo
    }],
    ['yellow_1', ()=>{
        //todo
    }],
    ['yellow_2', ()=>{
        //todo
    }],
    ['default_1', ()=>{
        //todo
    }],
])
let todo = todoList.get(`${color}_${status}`) || todoList.get('default');
todo.call(this);

这时,我们把二元判断的条件拼接成字符串,并用其为Map的键名。这种写法在多元条件判断时很好用。

当然,如果你觉得用字符串拼接有点变扭,你还可以这样:

const todoList = new Map([
    [{color:'bule',status:1}, ()=>{
        //todo
    }],
    [{color:'bule',status:2}, ()=>{
        //todo
    }],
    [{color:'yellow',status:1}, ()=>{
        //todo
    }],
    [{color:'yellow',status:2}, ()=>{
        //todo
    }],
    ['default', ()=>{
        //todo
    }],
])

这里我们使用了对象作为键名。这就是Map比Object的有优点的地方,即Map可以用任何类型的数据作为Key

进一步优化- 将处理逻辑缓存

const fnA = () => {}
const fnB = () => {}

const todoList = new Map([
    [/^color_[1-3]$/,fnA],
    ['default', fnB],
])
let todo = [...todoList()].filter(([key,value])=>(key.test(`${color}_${status}`)))
todo.forEach(([key,value])=>value.call(this))

这里,我们使用正则作为Map的key,符合正则的条件就会被执行。

总结

从上面的案例中,我们知道,判断可以从if-elseswitchObjectMap几种方式进行处理,Map不是绝对的,每种方式都有它适用的场景。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蟹蟹蟹风流

期望和你分享一杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值