Skip to main content

替换 if 和 else

单一条件

const getOwner = () => {
if (pjtName === "项目A") {
return "张三";
} else if (pjtName === "项目B") {
return "李四";
} else if (pjtName === "项目C") {
return "王五";
} else {
return "小马哥";
}
};

重构以上代码

案例一

const getOwner2 = (pjtName) => {
const map = {
项目A: "张三",
项目B: "李四",
项目C: "王五",
};
return map[pjtName] ? map[pjtName] : "小马哥";
};

案例二

const commodity = new Map([
["phone", 1999],
["computer", 9999],
["television", 2999],
["gameBoy", 3999],
]);

const price = (name) => {
return commodity.get(name);
};
price("phone"); // 1999

复合条件

案例一

const getImg = (res) => {
// 未中奖
if (res.type === 0) {
return "pic1";
}
// 现金
if (res.type === 1 && res.count === 6.6) {
return "pic2";
}
if (res.type === 1 && res.count === 6.6) {
return "pic3";
}
// 会员卡
if (res.type === 2 && res.count === 1) {
return "pic4";
}
if (res.type === 2 && res.count === 3) {
return "pic5";
}
if (res.type === 2 && res.count === 5) {
return "pic6";
}
if (res.type === 2 && res.count === 31) {
return "pic7";
}
if (res.type === 2 && res.count === 365) {
return "pic8";
}
// 优惠卷
if (res.type === 3) {
return "pic9";
}
};

重构

const refactoGetImg = (res) => {
const arr = [
[0, false, "pic1"],
[1, 6.6, "pic2"],
[1, 8.8, "pic3"],
[2, 1, "pic4"],
[2, 3, "pic5"],
[2, 5, "pic6"],
[2, 31, "pic7"],
[2, 365, "pic8"],
[3, false, "pic9"],
];
return arr.filter((item) => {
return (
res.type === item[0] &&
(res.count === item[1] || !!res.count === !!item[1])
);
})[0][2];
};

调用

console.log(refactoGetImg({ type: 0 }));
console.log(refactoGetImg({ type: 1, count: 6.6 }));
console.log(refactoGetImg({ type: 3 }));

案例二

if (this.caseSource.length > 0) {
this.formItem.caseSource = this.caseSource.join(",");
}

if (this.penaltiesType.length > 0) {
this.formItem.penaltiesType = this.penaltiesType.join(",");
}

if (this.administrativeStrongEnforce.length > 0) {
this.formItem.administrativeStrongEnforce =
this.administrativeStrongEnforce.join(",");
}

if (this.administrativeReconsideration.length > 0) {
this.formItem.administrativeReconsideration =
this.administrativeReconsideration.join(",");
}

if (this.administrativeLitigation.length > 0) {
this.formItem.administrativeLitigation =
this.administrativeLitigation.join(",");
}

重构为

let init = [
"caseSource",
"penaltiesType",
"administrativeStrongEnforce",
"administrativeReconsideration",
"administrativeLitigation",
];
for (var i = 0; i < init.length; i++) {
let item = init[i];
if (this[item].length > 0) {
this.formItem[item] = this[item].join(",");
}
}