写好 JS 条件语句的 5 条守则

论坛 期权论坛 期权     
Vue中文社区   2019-7-27 14:59   4050   0
在用 JavaScript 工作时,我们经常和条件语句打交道,这里有5条让你写出更好/干净的条件语句的建议。

1.多重判断时使用 Array.includes
2.更少的嵌套,尽早 return
3.使用默认参数和解构
4.倾向于遍历对象而不是 Switch 语句
5.对 所有/部分 判断使用 Array.every & Array.some
6.总结
[h2]1.多重判断时使用 Array.includes[/h2]让我们看一下下面这个例子:
  1. // condition
  2. function test(fruit) {
  3.   if (fruit == 'apple' || fruit == 'strawberry') {
  4.     console.log('red');
  5.   }
  6. }
复制代码

第一眼,上面这个例子看起来没问题。如果我们有更多名字叫 cherry 和 cranberries 的红色水果呢?我们准备用更多的 || 来拓展条件语句吗?


我们可以用 Array.includes (Array.includes)重写条件语句。

  1. function test(fruit) {
  2.   const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  3.   if (redFruits.includes(fruit)) {
  4.     console.log('red');
  5.   }
  6. }
复制代码
我们把红色的水果(red fruits)这一判断条件提取到一个数组。这样一来,代码看起来更整洁。
[h2]2.更少的嵌套,尽早 Return[/h2]让我们拓展上一个例子让它包含两个条件。

  • 如果没有传入参数 fruit,抛出错误
  • 接受 quantity 参数,并且在 quantity 大于 10 时打印出来

  1. function test(fruit, quantity) {
  2.   const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  3.   // 条件 1: fruit 必须有值
  4.   if (fruit) {
  5.     // 条件 2: 必须是red的
  6.     if (redFruits.includes(fruit)) {
  7.       console.log('red');
  8.       // 条件 3: quantity大于10
  9.       if (quantity > 10) {
  10.         console.log('big quantity');
  11.       }
  12.     }
  13.   } else {
  14.     throw new Error('No fruit!');
  15.   }
  16. }
  17. // 测试结果
  18. test(null); // error: No fruits
  19. test('apple'); // print: red
  20. test('apple', 20); // print: red, big quantity
复制代码
在上面的代码, 我们有:

  • 1个 if/else 语句筛选出无效的语句
  • 3层if嵌套语句 (条件 1, 2 & 3)


我个人遵循的规则一般是在发现无效条件时,尽早Return。
  1. /_ 当发现无效语句时,尽早Return _/
  2. function test(fruit, quantity) {
  3.   const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  4.   // 条件 1: 尽早抛出错误
  5.   if (!fruit) throw new Error('No fruit!');
  6.   // 条件 2: 必须是红色的
  7.   if (redFruits.includes(fruit)) {
  8.     console.log('red');
  9.     // 条件 3: 必须是大质量的
  10.     if (quantity > 10) {
  11.       console.log('big quantity');
  12.     }
  13.   }
  14. }
复制代码
这样一来,我们少了一层嵌套语句。这种编码风格非常好,尤其是当你有很长的if语句的时候(想象你需要滚动到最底层才知道还有else语句,这并不酷)

我们可以通过 倒置判断条件 & 尽早return 进一步减少if嵌套。看下面我们是怎么处理判断 条件2 的:
  1. /_ 当发现无效语句时,尽早Return _/
  2. function test(fruit, quantity) {
  3.   const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  4.   // 条件 1: 尽早抛出错误
  5.   if (!fruit) throw new Error('No fruit!');
  6.   // 条件 2: 当水果不是红色时停止继续执行
  7.   if (!redFruits.includes(fruit)) return;
  8.   console.log('red');
  9.   // 条件 3: 必须是大质量的
  10.   if (quantity > 10) {
  11.     console.log('big quantity');
  12.   }
  13. }
复制代码
通过倒置判断条件2,我们的代码避免了嵌套语句。这个技巧在我们需要进行很长的逻辑判断时是非常有用的,特别是我们希望能够在条件不满足时能够停止下来进行处理。

而且这么做并不困难。问问自己,这个版本(没有嵌套)是不是比之前的(两层条件嵌套)更好,可读性更高?

但对于我,我会保留先前的版本(包含两层嵌套)。这是因为:

  • 代码比较短且直接,包含if嵌套的更清晰
  • 倒置判断条件可能加重思考的负担(增加认知载荷)

因此,应当尽力减少嵌套和尽早return,但不要过度。如果你感兴趣的话,可以看一下关于这个话题的一篇文章和 StackOverflow 上的讨论。


  • Avoid Else, Return Early by Tim Oxley
  • StackOverflow discussion on if/else coding style
[h2]3.使用默认参数和解构[/h2]我猜下面的代码你可能会熟悉,在JavaScript中我们总是需要检查 null / undefined的值和指定默认值:
  1. function test(fruit, quantity) {
  2.   if (!fruit) return;
  3.   // 如果 quantity 参数没有传入,设置默认值为 1
  4.   const q = quantity || 1;
  5.   console.log(`We have ${q} ${fruit}!`);
  6. }
  7. //test results
  8. test('banana'); // We have 1 banana!
  9. test('apple', 2); // We have 2 apple!
复制代码
实际上,我们可以通过声明 默认函数参数 来消除变量 q。
  1. function test(fruit, quantity = 1) {
  2.   // 如果 quantity 参数没有传入,设置默认值为 1
  3.   if (!fruit) return;
  4.   console.log(`We have ${quantity} ${fruit}!`);
  5. }
  6. //test results
  7. test('banana'); // We have 1 banana!
  8. test('apple', 2); // We have 2 apple!
复制代码
这更加直观,不是吗?注意,每个声明都有自己的默认参数.

例如,我们也能给fruit分配默认值:function test(fruit = 'unknown', quantity = 1)。

如果fruit是一个object会怎么样?我们能分配一个默认参数吗?
  1. function test(fruit) {
  2.   // 当值存在时打印 fruit 的值
  3.   if (fruit && fruit.name)  {
  4.     console.log (fruit.name);
  5.   } else {
  6.     console.log('unknown');
  7.   }
  8. }
  9. //test results
  10. test(undefined); // unknown
  11. test({ }); // unknown
  12. test({ name: 'apple', color: 'red' }); // apple
复制代码
看上面这个例子,我们想打印 fruit 对象中可能存在的 name 属性。否则我们将打印unknown。我们可以通过默认参数以及解构从而避免判断条件 fruit && fruit.name
  1. // 解构 - 仅仅获取 name 属性
  2. // 为其赋默认值为空对象
  3. function test({name} = {}) {
  4.   console.log (name || 'unknown');
  5. }
  6. // test results
  7. test(undefined); // unknown
  8. test({ }); // unknown
  9. test({ name: 'apple', color: 'red' }); // apple
复制代码
由于我们只需要 name 属性,我们可以用 {name} 解构出参数,然后我们就能使用变量 name 代替 fruit.name。

我们也需要声明空对象 {} 作为默认值。如果我们不这么做,当执行 test(undefined) 时,你将得到一个无法对 undefined 或 null 解构的的错误。因为在 undefined 中没有 name 属性。

如果你不介意使用第三方库,这有一些方式减少null的检查:

  • 使用 Lodash get函数
  • 使用Facebook开源的idx库(with Babeljs)

这是一个使用Lodash的例子:
  1. function test(fruit) {
  2.   // 获取属性名,如果属性名不可用,赋默认值为 unknown
  3.   console.log(__.get(fruit, 'name', 'unknown');
  4. }
  5. // test results
  6. test(undefined); // unknown
  7. test({ }); // unknown
  8. test({ name: 'apple', color: 'red' }); // apple
复制代码
你可以在jsbin运行demo代码。除此之外,如果你是函数式编程的粉丝,你可能选择使用 Lodash fp,Lodash的函数式版本(方法变更为get或者getOr)。
[h2]4.倾向于对象遍历而不是Switch语句[/h2]让我们看下面这个例子,我们想根据 color 打印出水果:
  1. function test(color) {
  2.   // 使用条件语句来寻找对应颜色的水果
  3.   switch (color) {
  4.     case 'red':
  5.       return ['apple', 'strawberry'];
  6.     case 'yellow':
  7.       return ['banana', 'pineapple'];
  8.     case 'purple':
  9.       return ['grape', 'plum'];
  10.     default:
  11.       return [];
  12.   }
  13. }
  14. // test results
  15. test(null); // []
  16. test('yellow'); // ['banana', 'pineapple']
复制代码
上面的代码看起来没有错误,但是我找到了一些累赘。用对象遍历实现相同的结果,语法看起来更简洁:

  1. const fruitColor = {
  2.   red: ['apple', 'strawberry'],
  3.   yellow: ['banana', 'pineapple'],
  4.   purple: ['grape', 'plum']
  5. };
  6. function test(color) {
  7.   return fruitColor[color] || [];
  8. }
复制代码
或者你也可以使用 Map实现相同的结果:
  1.   const fruitColor = new Map()
  2.     .set('red', ['apple', 'strawberry'])
  3.     .set('yellow', ['banana', 'pineapple'])
  4.     .set('purple', ['grape', 'plum']);
  5. function test(color) {
  6.   return fruitColor.get(color) || [];
  7. }
复制代码
Map是一种在 ES2015 规范之后实现的对象类型,允许你存储 key 和 value 的值。

但我们是否应当禁止switch语句的使用呢?答案是不要限制你自己。从个人来说,我会尽可能的使用对象遍历,但我并不严格遵守它,而是使用对当前的场景更有意义的方式。

Todd Motto有一篇关于 switch 语句对比对象遍历的更深入的文章,你可以在这个地方阅读
[h2]TL;DR; 重构语法[/h2]在上面的例子,我们能够用Array.filter 重构我们的代码,实现相同的效果。
  1. const fruits = [
  2.     { name: 'apple', color: 'red' },
  3.     { name: 'strawberry', color: 'red' },
  4.     { name: 'banana', color: 'yellow' },
  5.     { name: 'pineapple', color: 'yellow' },
  6.     { name: 'grape', color: 'purple' },
  7.     { name: 'plum', color: 'purple' }
  8. ];
  9. function test(color) {
  10.   return fruits.filter(f => f.color == color);
  11. }
复制代码
有着不止一种方法能够实现相同的结果,我们以上展示了 4 种。
[h2]5.对 所有/部分 判断使用Array.every & Array.some[/h2]这最后一个建议更多是关于利用 JavaScript Array 的内置方法来减少代码行数。看下面的代码,我们想要检查是否所有水果都是红色:
  1. const fruits = [
  2.     { name: 'apple', color: 'red' },
  3.     { name: 'banana', color: 'yellow' },
  4.     { name: 'grape', color: 'purple' }
  5.   ];
  6. function test() {
  7.   let isAllRed = true;
  8.   // 条件:所有水果都是红色
  9.   for (let f of fruits) {
  10.     if (!isAllRed) break;
  11.     isAllRed = (f.color == 'red');
  12.   }
  13.   console.log(isAllRed); // false
  14. }
复制代码
代码那么长!我们可以通过 Array.every减少代码行数:
  1. const fruits = [
  2.     { name: 'apple', color: 'red' },
  3.     { name: 'banana', color: 'yellow' },
  4.     { name: 'grape', color: 'purple' }
  5.   ];
  6. function test() {
  7.   const isAllRed = fruits.every(f => f.color == 'red');
  8.   console.log(isAllRed); // false
  9. }
复制代码
现在更简洁了,不是吗?相同的方式,如果我们想测试是否存在红色的水果,我们可以使用 Array.some 一行代码实现。
  1. const fruits = [
  2.     { name: 'apple', color: 'red' },
  3.     { name: 'banana', color: 'yellow' },
  4.     { name: 'grape', color: 'purple' }
  5. ];
  6. function test() {
  7.   // 条件:任何一个水果是红色
  8.   const isAnyRed = fruits.some(f => f.color == 'red');
  9.   console.log(isAnyRed); // true
  10. }
复制代码
[h2]6.总结[/h2]让我们一起生产更多可读性高的代码。我希望你能从这篇文章学到东西。
这就是所有的内容。编码快乐

英文:ecelyn Yeen  译文:眠云(杨涛)

往期
GMTC 大前端时代前端监控的最佳实践

如何写出让同事无法维护的代码?

福利:扫描下方二维码回复爪哇教育即可得高级前端全栈课程视频及前端资料一份


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:20
帖子:4
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP