美文网首页
优化 if - else代码

优化 if - else代码

作者: 一长亭 | 来源:发表于2017-10-11 10:34 被阅读0次

在javascript流程控制中并没有像java中有goto跳转,所以基本上都是用if...if 或者if...else if来控制。但是,如果流程有比较多的分支时,代码会显得特别的肿。本文介绍了一种简单的消肿方法,请参考。

1.明白if...ifif...else if的区别

if (条件1)
{
    //语句1
}

if (条件2)
{
    //语句2
}

这种格式中,程序会依次判断条件1和条件2是否成立并根据结果决定是否执行语句1和语句2,也就是说,第一个 if 块和第二个 if 块没有影响(除非在执行第一个 if 块的时候就凶残地 return 了)

而下面这种格式,

if (条件1) 
{
    //语句1
}
else if (条件2)
{
    //语句2
}

if 块和 else if 块本质上是互斥的!也就是说,一旦语句1得到了执行,程序会跳过 else if 块,else if 块中的判断语句以及语句2一定会被跳过;同时语句2的执行也暗含了条件1判断失败和语句1没有执行;当然还有第3个情况,就是条件1和条件2都判断失败,语句1和语句2都没有得到执行。

2.未优化的代码

      function program(a) {
        if (a === 'java') {
          console.log('the language is: ' + a);
        } else if (a === 'object c') {
          console.log('the language is: ' + a);
        } else if (a === 'js') {
          console.log('the language is: ' + a);
        }
        // 中间还有若干个 else if ...
        else {
          console.log('the language is: php');
        }
      }
      
      program('java'); // the language is: java

一个词来形容:恶心

3.尝试优化
原理:映射对应

      const programs = {
        java: function (a) {
          console.log('the language is: ' + a);
        },
        object: function (a) {
          console.log('the language is: ' + a);
        },
        js: function (a) {
          console.log('the language is: ' + a);
        }
      };

      (function sayPrograms(){
        return programs['java']('javaaaaaaaa'); // the language is: javaaaaaaaa
      })();

对于if - else-if - else 类型的处理:使用try-catch

      const programs = {
        java: function (a) {
          console.log('the language is: ' + a);
        },
        object: function (a) {
          console.log('the language is: ' + a);
        },
        js: function (a) {
          console.log('the language is: ' + a);
        }
      };

      try {
        (function sayPrograms() {
          return programs['java']('javaaaaaaaa');
        })();
      } catch (err) {
        console.log('the language is: php');
      }

相关文章

网友评论

      本文标题:优化 if - else代码

      本文链接:https://www.haomeiwen.com/subject/ezviyxtx.html