首页 > 解决方案 > 如何缩短 if/else 语句

问题描述

我正在尝试缩短我创建的一系列 if/else 语句。代码工作得很好,但目前似乎是多余的。我试图实现一个循环来执行此操作,但我无法弄清楚如何处理循环中每个语句的“indexOf(”“)”。

这是我的代码:

    window.addEventListener("load", (event)=>{

      $("div.faq-container").hide();
    if (window.location.href.indexOf("shipping") > -1) {
      $("div.faq-container").eq( "0" ).show();
    }
    else if (window.location.href.indexOf("returns") > -1) {
      $("div.faq-container").eq( "1" ).show();
    }
    else if (window.location.href.indexOf("custom") > -1) {
      $("div.faq-container").eq( "2" ).show();
    }
    else if (window.location.href.indexOf("replacements") > -1) {
      $("div.faq-container").eq( "3" ).show();
    }
    else if (window.location.href.indexOf("mostFAQs") > -1) {
      $("div.faq-container").eq( "4" ).show();
    }
    else if (window.location.href.indexOf("RAD") > -1) {
      $("div.faq-container").eq( "5" ).show();
    }
    else if (window.location.href.indexOf("environmental") > -1) {
      $("div.faq-container").eq( "6" ).show();
    }
    else if (window.location.href.indexOf("USA") > -1) {
      $("div.faq-container").eq( "7" ).show();
    }
    else{
      $("div.faq-container").eq( "0" ).show();
    }

    })

有什么建议么?

标签: javascriptjqueryif-statement

解决方案


您可以只为每个值使用一个数组,数组也使用零索引,因此您可以在数组中使用 indexOf 来获取索引。

例如。

const lu = ['shipping', 'returns', 'custom', 'replacements',
  'mostFAQs', 'RAD', 'environmental', 'USA'
];

window.addEventListener("load", (event)=>{
  $("div.faq-container").hide();
  for (let ix = 0; ix < lu.length; ix += 1) {
    if (window.location.href.indexOf(lu[ix]) > -1) {
      $("div.faq-container").eq(ix.toString()).show();
      return;
    }  
  }
  $("div.faq-container").eq( "0" ).show();
});

推荐阅读