javascript - 如何缩短 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();
}
})
有什么建议么?
解决方案
您可以只为每个值使用一个数组,数组也使用零索引,因此您可以在数组中使用 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();
});
推荐阅读
- python - 从 While 循环创建一个新的 .CSV 文件
- c - 为什么我的函数不会被读取?我只是得到“错误:调用对象'FunctionName'不是函数或函数指针”
- r - pivot_longer summarise_each 的输出,带有 mean 和 sd 函数
- laravel - Laravel Upgrade 抛出错误,如何从 5.7 升级到 6.2?
- r - 使用通配符 r 删除文本替换
- c# - 如何使用 VS 2019 为我的应用程序构建在线安装程序
- java - Spring boot 中的 PostgreSQL 继承命名问题
- javascript - 缓存/预加载 SVG 文件反应原生
- drools - 如何使用 RestWorkItemHandler 调用需要 application/x-www-form-urlencoded content-type 的服务
- scala - 如何在 Scala 中处理嵌套的期货序列函数