龙空技术网

JavaScript中if-else和switch优雅写法

互联网知识分享 43

前言:

现时同学们对“jsif不等于”大概比较着重,同学们都想要知道一些“jsif不等于”的相关资讯。那么小编也在网上搜集了一些关于“jsif不等于””的相关文章,希望我们能喜欢,姐妹们一起来学习一下吧!

大家在写if..else..或者swtich时,是否通常会采用如下写法:

// if...else...const fn = (type) => {    if(type === 1){        console.log('11111')    }else if(type === 2){        console.log('22222')    }else{        console.log('33333')    }}// switchconst fn2 = (type) => {    switch(type){        case 1:            console.log('11111');            break;        case 2:            console.log('22222');            break;        case 3:            console.log('33333');            break;        default:            break;    }}

我们知道,上面这种写法是很常见的,但是一旦分支多了,是很难维护的。因此我们可以采用ES6提供的Map函数来优化。

const map = new Map([    [1, ()=> {console.log('1')}],    [2, ()=> {console.log('2')}],    [3, ()=> {console.log('3')}]])const fn = (type) => {    const func = map.get(type);    if(!func) return;    func();}

经过这样的优化以后,代码是不是可维护性更强了?

标签: #jsif不等于 #jsifelseifelse