干掉 if if的替代用法

21 阅读1分钟
// 假如有这样一段代码
if (type === "success") {
  return "green";
}
if (type === "warning") {
  return "yellow";
}
if (type === "error") {
  return "red";
}

// switch改造
switch (type) {
  case "success":
    return "green";
  case "warning":
    return "yellow";
  case "error":
    return "red";
}

// 对象映射改造
const typeMap = {
  success: "green",
  warning: "yellow",
  error: "red",
};
return typeMap[type];