【问题标题】:How can I turn this else if statement into a switch statement?如何将此 else if 语句转换为 switch 语句?
【发布时间】:2019-07-03 01:06:28
【问题描述】:

我创建了一个函数来每秒检查网站的当前 url 并根据某个值字符串更改 HTML 元素中的元标记图像。我的代码很完美,但是我想让我的代码更具可读性 7 优化......所以我想把这段代码变成 switch 语句,但我现在无法自己弄清楚。任何帮助将不胜感激。代码如下:

// Variable declarations
var imgOgSrc = $('meta[property="og:image"]');
var twitterImgSrc = $('meta[name="twitter:image:src"]');
var currentUrl;

// Checks for current url & changes meta tags depending on slug value
function getCurrentUrl(){
    currentUrl = window.location.href;

    if(currentUrl.toLowerCase().indexOf('python') >= 0) {
            imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
            twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
    }   else if (currentUrl.toLowerCase().indexOf('java') >= 0) {
            imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
            twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
    }   else if (currentUrl.toLowerCase().indexOf('php') >= 0) {
            imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
            twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
    }
        else {
            imgOgSrc.attr('content', currentUrl);
            twitterImgSrc.attr('content', currentUrl);
    }
}   

【问题讨论】:

  • then部分的区别在哪里?
  • 对于您的用例,if 语句将是可行的方法。查看这个进行速度测试的答案:*.com/a/12259830/3684265
  • 当您不寻找完全匹配时,使用 switch 毫无意义。
  • @ManuelAbascal,Nina 说在 if 语句的 attr 内容中的 URL 都是相同的。因此,如果这不是拼写错误,您只需要一个 if 和一个 else。
  • 我会以不同的方式匹配 url,我会结合 ifs,因为它是每个中相同的内容。

标签: javascript jquery switch-statement


【解决方案1】:

由于所有if 条件都具有相同的代码,您可以像这样使用some

function getCurrentUrl() {
  currentUrl = window.location.href;
  const customUrlNeeded = ['python', 'java', 'php'].some(a => currentUrl.toLowerCase().includes(a))

  if (customUrlNeeded) {
    imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
    twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
  } else {
    imgOgSrc.attr('content', currentUrl);
    twitterImgSrc.attr('content', currentUrl);
  }

}

【讨论】:

    【解决方案2】:

    试试这个:

    var currentUrl;
    
    function getCurrentUrl() {
      currentUrl = window.location.href.toLowerCase();
    
      var langType = function(type) {
        return currentUrl.indexOf(type) > -1;
      }
    
      switch (true) {
        case langType('python'):
          imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
          twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
          break;
    
        case langType('java'):
          // ...
          break;
    
        case langType('php'):
          // ...
          break;
    
        default:
          // ...
          break;
      }
    }
    

    【讨论】:

    • 是的,它会起作用,但这不是最好的解决方案。
    • 不是最好的,是的,我个人会亲自使用 Taki 的解决方案。只是试图坚持使用 OP 选择使用switch
    【解决方案3】:

    代替switch/case,您可以将图像存储在一个对象中,查看currentUrl 是否有关键字,提取它然后使用它从该对象中获取值:

    // Variable declarations
    var imgOgSrc = $('meta[property="og:image"]');
    var twitterImgSrc = $('meta[name="twitter:image:src"]');
    var currentUrl;
    
    function getCurrentUrl(){
      currentUrl = window.location.href.toLowerCase();
    
      const obj = {
        python : {
          imgOgSrc : 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg',
          twitterImgSrc :  'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg'
        },
        java : {
          imgOgSrc : 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg',
          twitterImgSrc :  'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg'
        },
        php : {
          imgOgSrc : 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg',
          twitterImgSrc :  'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg'
        }
      }
    
      const word = currentUrl.match(/php | java | python /gi)[0];
    
      if(word){
        imgOgSrc.attr('content', obj[word].imgOgSrc);
        twitterImgSrc.attr('content', obj[word].twitterImgSrc);    
      }
      else {
        imgOgSrc.attr('content', currentUrl);
        twitterImgSrc.attr('content', currentUrl);
      }
    }   
    

    【讨论】:

      【解决方案4】:

      您可以使用 imgOgSrctwitterImgSrc 属性为 pythonjavaphp 获取一个对象,并使用 null 属性来处理不匹配的 URL。

      function getTarget(url) {
          const targets = { 
              python: {
                  imgOgSrc: 'data1',
                  twitterImgSrc: 'data2'
              },
              java: {
                  imgOgSrc: 'data3',
                  twitterImgSrc: 'data4'
              },
              php: {
                  imgOgSrc: 'data5',
                  twitterImgSrc: 'data6'
              },
              null: {                    // default values
                  imgOgSrc: 'data7',
                  twitterImgSrc: 'data8'
              }
          };
          return targets[url.toLowerCase().match(new RegExp(Object.keys(targets).join('|')))];
      }
      
      console.log(getTarget('blablajavabla'));
      console.log(getTarget('blablabla'));

      【讨论】: