概述
最近公司要求优化之前项目的代码,去掉if…else…之类的。
情况一:
if (this.devstate == 1) {
this.functionTag = "AA";
this.strValue = 1;
} else if (this.devstate == 2) {
this.functionTag = "AA";
this.strValue = 0;
} else if (this.devstate == 3) {
this.functionTag = "BB";
this.strValue = 1;
} else if (this.devstate == 4 {
this.functionTag = "BB";
this.strValue = 100;
}...
if (this.devstate !== 0) {
this.paramsBody.functionTag = this.functionTag;
this.paramsBody.strValue = this.strValue;
}
优化:
let actions = new Map([
[1, ["AA", 1]],
[2, ["AA", 0]],
[3, ["BB", 1]],
[4, ["BB", 100]],
...
])
let funTag
let str
function selectedTag (status) {
//由于这里不可直接调用this.functionTag,所以需要先声明,再赋值
let action = actions.get(status)
funTag = action[0];
str = action[1]
}
if (this.devstate !== 0) {
selectedTag(this.devstate)
this.functionTag = funTag
this.strValue = str
this.paramsBody.functionTag = this.functionTag;
this.paramsBody.strValue = this.strValue;
}
情况二:
if (el.functionTag === "AA") {
if (el.strValue === "1") {
body.event = "上线";
body.flag = "AA_1";
} else {
body.event = "离线";
body.flag = "AA_0";
}
} else if (el.functionTag === "BB" || el.functionTag === "CC") {
if (el.strValue === "1") {
body.event = "报警";
body.flag = "BB_1";
} else {
body.event = "非报警状态";
body.flag = "BB_0";
}
} else if (el.functionTag === "CC") {
body.event = "设备电量属性:" + el.strValue + "%";
body.flag = "CC";
}
优化:
const showActions = new Map([
// 当不写srtValue,则作为已有的strValue的else
[{ functionTag: "AA", strValue: "1" }, () => {
body.event = "上线";
body.flag = "AA_1";
}],
[{ functionTag: "AA" }, () => {
body.event = "上线";
body.flag = "AA_0";
}],
[{ functionTag: "BB", strValue: "1" }, () => {
body.event = "报警";
body.flag = "BB_1";
}],
[{ functionTag: "BB" }, () => {
body.event = "非报警状态";
body.flag = "BB_0";
}],
[{ functionTag: "CC", strValue: "1" }, () => {
body.event = "报警";
body.flag = "CC_1";
}],
[{ functionTag: "CC" }, () => {
body.event = "非报警状态";
body.flag = "CC_0";
}],
[{ functionTag: "DD" }, () => {
body.event = "设备电量属性:" + el.strValue + "%"; //这里直接使用el.strValue也可
body.flag = "DD";
}]
])
function onButtonClick (funcTag, strMsg) {
// 根据条件使用filter查询
let action = [...showActions].filter(
([key, value]) => {
if (!key.strValue) {
return key.functionTag === funcTag
}
key.strValue === strMsg && key.functionTag === funcTag
},
);
action.forEach(([key, value]) => {
value.call(this)
});
}
onButtonClick(el.functionTag, el.strValue)
最后
以上就是背后鲜花为你收集整理的JS优化if...else的全部内容,希望文章能够帮你解决JS优化if...else所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复