【问题标题】:Simplifying a switch case in JavaScript简化 JavaScript 中的 switch case
【发布时间】:2012-08-14 10:18:00
【问题描述】:

我有一个相当重复的 switch case 语句,为了学习最简单的做事方式,我想转向 SO,看看是否有更优雅的解决方案:

        switch(id)
        {
            case 'ib-02a':
                if(direction == 'left')
                    setHash('ib-02b');
                break;
            case 'ib-02b':
                if(direction == 'right')
                    setHash('ib-02a');
                if(direction == 'left')
                    setHash('ib-02c');
                break;
            case 'ib-02c':
                if(direction == 'right')
                    setHash('ib-02b');
                if(direction == 'left')
                    setHash('ib-02d');
                break;
            case 'ib-02d':
                if(direction == 'right')
                    setHash('ib-02c');
            break;

            case 'ib-03a':
                if(direction == 'left')
                    setHash('ib-03b');
                break;
            case 'ib-03b':
                if(direction == 'right')
                    setHash('ib-03a');
                if(direction == 'left')
                    setHash('ib-03c');
                break;
            case 'ib-03c':
                if(direction == 'right')
                    setHash('ib-03b');
                if(direction == 'left')
                    setHash('ib-03d');
                break;
            case 'ib-03d':
                if(direction == 'right')
                    setHash('ib-03c');
            break;

            case 'pb-05a':
                if(direction == 'left')
                    setHash('pb-05b');
                break;
            case 'pb-05b':
                if(direction == 'right')
                    setHash('pb-05a');
                if(direction == 'left')
                    setHash('pb-05c');
                break;
            case 'pb-05c':
                if(direction == 'right')
                    setHash('pb-05b');
                if(direction == 'left')
                    setHash('pb-05d');
                break;
            case 'pb-05d':
                if(direction == 'right')
                    setHash('pb-05c');
            break;
        }

我正在读取滑动事件,如果我正在滑动的元素的 ID 与 ib-02*、ib-03* 或 pb-05* 匹配,我正在为适当的 ID 调用 setHash 函数。如果我在 *a 上滑动,我向左滑动到 *b。如果我在 *b 上滑动,我向右滑动到 *a 并向左滑动到 *c。以此类推,总是在 *a 和 *d 之间。

必须有一种重复性较低的方法来做到这一点,但我不确定最好的方法到底是什么。

【问题讨论】:

    标签: javascript jquery switch-statement swipe


    【解决方案1】:

    如何将它们映射到一个对象?然后只需将setHash 与检索到的值一起使用。

    var ids = {
        'pb-05c' : {
            left : 'pb-05d',
            right : 'pb-05b'
        }
        ...
    }
    
    function setHashes(id,direction){
        if(id && ids[id]){
            id = ids[id];
            if(direction && id[direction]){
                setHash(id[direction]);
            }
        }
    }
    

    都是检索,没有条件评估,对性能有好处。

    【讨论】:

    • 如果您的数据结构中不存在 id 或方向,则此代码会出现问题(原始代码没有)。
    • @jfriend00 是的,我只是在考虑。
    • 我喜欢这个,但我想知道如何解决如果没有 id 或 direction 传递的问题?
    • @Greg-J 更新了我的答案。您只需检查 id 和 direction 是否存在。
    【解决方案2】:

    abcd这4种主要情况,你可以将你的switch语句基于这些字符串,试试这个:

    var c = id.slice(0, 5); // "ib-02" or "ib-03" or "ib-04" ...
    var which = id.slice(-1); // "a" or "b" or "c" or "d"
    switch(which) {
        case 'a':
           if(direction == 'left')
                 setHash(c+'b');
              break;
        case 'b':
           if(direction == 'right')
                 setHash(c+'a');
           if(direction == 'left')
                 setHash(c+'c');
              break;
        case 'c':
           if(direction == 'right')
                 setHash(c+'b');
           if(direction == 'left')
                 setHash(c+'d');
              break;
        case 'd':
           if(direction == 'right')
                setHash(c+'c');
              break;
    }
    

    【讨论】:

      【解决方案3】:

      您可以像这样驱动整个数据表:

      var logicData = {
          // format is the id first and then an array with the left, then right value for the hash
          // leave an item as an empty string if you don't ever want to go that direction
          'ib-02a': ['ib-02b', ''],
          'ib-02b': ['ib-02c', 'ib-02a'],
          'ib-02c': ['ib-02d', 'ib-02d']
          // fill in the rest of the data table here
      };
      
      function setNewHash(id, direction) {
          var hash, data = logicData[id];
          if (data) {
              if (direction == 'left') {
                  hash = data[0];
              } else if (direction == 'right') {
                  hash = data[1];
              }
              if (hash) {
                  setHash(hash);
              }
          }
      }
      

      【讨论】:

        【解决方案4】:
        id='ib-02a'; //you have string id, this one is for demo
        id=[id.slice(0,--id.length), id.charAt(--id.length)];
        
        switch(id[1]){
            case 'a':
                if(direction == 'left'){setHash(id[0]+'b');}
                break;
            case 'b':
                if(direction =='right'){setHash(id[0]+'a');}
                if(direction == 'left'){setHash(id[0]+'c');}
                break;
            case 'c':
                if(direction == 'right'){setHash(id[0]+'b');}
                if(direction == 'left'){setHash(id[0]+'d');}
                break;
            case 'd':
                if(direction == 'right'){setHash(id[0]+'c');}
                break;
        }
        

        如果案例 b 和 c 只是“左”或“右”,您可以在这些 if 语句中使用 else

        【讨论】:

        • 忘了提一下:这不会在其父范围内创建新变量,id 可以在需要时简单地在之后重建:id=id.join('');
        【解决方案5】:

        我喜欢 undefined 和 GitaarLab 的总体方向,他们实际上解决了算法并实现了算法。回顾一下,该算法基本上是left 增加最后一个字母,right 减少 id 的最后一个字母,但你不要低于a 或高于d。所以,我做了一个紧凑的实现,我将最后一个字母转换为数字并直接增加或减少它,而不是使用 if/else 或 case 语句:

        function setNewHash(id, direction) {
            var base = id.substr(0, 5);
            var tag = id.charCodeAt(5), newTag;
            var nav = {left: 1, right: -1};
            var delta = nav[direction];
            if (delta) {
                tag += delta;
                newTag = String.fromCharCode(tag);
                if (newTag >= 'a' && newTag <= 'd') {
                    setHash(base + newTag);
                }
            }
        }
        

        工作测试用例:http://jsfiddle.net/jfriend00/gwfLD/

        【讨论】:

        • 谢谢夸奖!!我也喜欢你的可重用功能。我也在查看direction 部分,但不知道它的确切限制。 +1
        【解决方案6】:

        您可以将 id 分成不同的部分,然后在您执行 setHash 之前重新构建它们。

        function chunkId(id) {
            // use a regex or string split or something to convert
            // "ib-05a" to ["ib-05", "a"]
            return ["ib-05", "a"];
        }
        
        function next(str) {
            // return the next letter in the alphabet here
            return "b";
        }
        
        function prev(str) {
            // return the prev letter in the alphabet here
            return "b";
        }
        
        function swipe (id, direction) {
            var array = chunkId(id);
            // you can only swipe left if not on "d"
            if (direction === "left" && id[1] != "d") {
                setHash(id[0] + next(id[1])); // build hash based on next character
            }
            // you can only swipe right if not on "a"
            if (direction === "right" && id[1] != "a") {
                setHash(id[0] + prev(id[1])); // build hash based on prev character
            }
        }
        

        【讨论】:

          【解决方案7】:

          您可以切换 id 和 direction 检查以使其更清晰:

          switch (direction) {
            case 'left':
              switch (id) {
                case 'ib-02a': setHash('ib-02b'); break;
                case 'ib-02b': setHash('ib-02c'); break;
                case 'ib-02c': setHash('ib-02d'); break;
                case 'ib-03a': setHash('ib-03b'); break;
                case 'ib-03b': setHash('ib-03c'); break;
                case 'ib-03c': setHash('ib-03d'); break;
                case 'pb-05a': setHash('pb-05b'); break;
                case 'pb-05b': setHash('pb-05c'); break;
                case 'pb-05c': setHash('pb-05d'); break;
              }
              break;
            case 'right':
              switch (id) {
                case 'ib-02b': setHash('ib-02a'); break;
                case 'ib-02c': setHash('ib-02b'); break;
                case 'ib-02d': setHash('ib-02c'); break;
                case 'ib-03b': setHash('ib-03a'); break;
                case 'ib-03c': setHash('ib-03b'); break;
                case 'ib-03d': setHash('ib-03c'); break;
                case 'pb-05b': setHash('pb-05a'); break;
                case 'pb-05c': setHash('pb-05b'); break;
                case 'pb-05d': setHash('pb-05c'); break;
              }
              break;
          }
          

          那么你可以通过拆分id来简化if:

          var first = id.substr(0, 5);
          var last = id.substr(6);
          switch (direction) {
            case 'left':
              switch (last) {
                case 'a': setHash(first + 'b'); break;
                case 'b': setHash(first + 'c'); break;
                case 'c': setHash(first + 'd'); break;
              }
              break;
            case 'right':
              switch (last) {
                case 'b': setHash(first + 'a'); break;
                case 'c': setHash(first + 'b'); break;
                case 'd': setHash(first + 'c'); break;
              }
              break;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-09-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多