前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >?️ 一种使用 if-else / switch 更好的方式

?️ 一种使用 if-else / switch 更好的方式

作者头像
皮小蛋
发布2021-05-08 11:50:03
4350
发布2021-05-08 11:50:03
举报
文章被收录于专栏:前端皮小蛋前端皮小蛋

is-else & switch

背景

今天面试了一天, 累坏了, 发一篇简单的, 示例代码参考了Jack Taylor。

前两天做 Code Review 的时候, 发现很多 if-else / switch 语句,并不是特别优雅。在一些逻辑复杂的地方,看起来比较臃肿, 不是那么好读。

举个例子:

代码语言:javascript
复制
function getTranslation(rhyme) {
  const lowercasedRhyme = rhyme.toLowerCase();
  if ( lowercasedRhyme === "apples and pears") {
    return "Stairs";
  } else if (lowercasedRhyme === "hampstead heath") {
    return "Teeth";
  } else if (lowercasedRhyme === "loaf of bread") {
    return "Head";
  } else if (lowercasedRhyme === "pork pies") {
    return "Lies";
  } else if (lowercasedRhyme === "whistle and flute") {
    return "Suit";
  }
  return "Rhyme not found";
}

这样做看起来十分臃肿, 而且做了太多 lowercasedRhyme === 'xxx'的判断, 以后有一个新的分支, 都需要判断一次。

如果换成 switch 语句:

代码语言:javascript
复制
function getTranslation(rhyme) {
  switch (rhyme.toLowerCase()) {
    case "apples and pears":
      return "Stairs";
    case "hampstead heath":
      return "Teeth";
    case "loaf of bread":
      return "Head";
    case "pork pies":
      return "Lies";
    case "whistle and flute":
      return "Suit";
    default:
      return "Rhyme not found";
  }
}

情况有所改善, 但是依旧显得臃肿,我们只需要返回一个值。

遇到具有更复杂的功能时,也很容易错过 break声明, 造成错误。

再换一种方式:

代码语言:javascript
复制
function getTranslationMap(rhyme) {
  const rhymes = {
    "apples and pears": "Stairs",
    "hampstead heath": "Teeth",
    "loaf of bread": "Head",
    "pork pies": "Lies",
    "whistle and flute": "Suit",
  };
  return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
}

我们直接使用 key-value 的形式去取用数据, 最后用 ?? 最为兜底。

这里的 ??, 就是所谓的空位合并运算符 :

代码语言:javascript
复制
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

不熟悉的朋友, 可以去看一下文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

如果遇到了更复杂一点的逻辑, 在适合的场景也可以用这种方式来做, 比如:

代码语言:javascript
复制
function calculate(num1, num2, action) {
  const actions = {
    add: (a, b) => a + b,
    subtract: (a, b) => a - b,
    multiply: (a, b) => a * b,
    divide: (a, b) => a / b,
  };

  return actions[action]?.(num1, num2) ?? "Calculation is not recognised";
}

有一点注意一下,这里我们同时用到了 ?.?? 操作符。

结论

今天讨论的这个问题,其实比较主观, 带有一定的个人偏好。

代码的可读性可维护性, 应该是我们都需要注意的。

今天的内容就这么多

希望对大家有所帮助 :)

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-04-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端皮小蛋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 背景
  • 结论
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档