Javascript 如何缩短if/else语句
我试图缩短我创建的一系列if/else语句。代码运行得很好,但目前似乎是多余的。我试图实现一个循环来实现这一点,但我不知道如何处理循环中每个语句的indexOf 这是我的密码:Javascript 如何缩短if/else语句,javascript,jquery,if-statement,Javascript,Jquery,If Statement,我试图缩短我创建的一系列if/else语句。代码运行得很好,但目前似乎是多余的。我试图实现一个循环来实现这一点,但我不知道如何处理循环中每个语句的indexOf 这是我的密码: window.addEventListener("load", (event)=>{ $("div.faq-container").hide(); if (window.location.href.indexOf("shipping&q
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 url=window.location.href const routes=[运输、退货、定制、更换、mostFAQs、RAD、环境、美国] 设解=假 对于routes.entries的const{index,route}{ 如果url.indexOfroute>-1{ $div.faq-container.eq`${index}`.show 解决方案=真 } } 如果解决方案$div.faq-container.eq0.show
您可以将这些键放入一个有序的数组中,并循环遍历它们以查看它们是否包含在url中。some循环在找到真值时退出 将初始键值设置为0,因为这是else情况 const key=['shipping','returns','custom','replacements','mostFAQs','RAD','environment','USA']; 设foundKey=0; keys.somekey,索引=>{ 如果window.location.href.indexOfkey>-1{ foundKey=索引; 返回true; } 返回false; }; $div.faq-container.eqfoundKey.show;
请在此处查看Javascript中的开关情况:。此问题可能更适合于。
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();
});