javascript中if语句中的多个条件
我知道有这样一个问题,但我的有点不同,它已经起作用了,但我不知道如何简化它javascript中if语句中的多个条件,javascript,Javascript,我知道有这样一个问题,但我的有点不同,它已经起作用了,但我不知道如何简化它 if(location.pathname==`/`location.pathname===`/kurikulum/`location.pathname==`/pengembangan diri/`location.pathname====`/statistik/`| location.pathname==`/teknologi/`location.pathname==`/ekonomi/`location.pathnam
if(location.pathname==`/`location.pathname===`/kurikulum/`location.pathname==`/pengembangan diri/`location.pathname====`/statistik/`| location.pathname==`/teknologi/`location.pathname==`/ekonomi/`location.pathname====`/desain/`/corona
正如您所看到的,它并不漂亮,我想知道我们是否可以不重复location.pathname
这是关于盖茨比的,但这是一个javascript问题您可以通过定义一个javascript对象数组来简化,如下所示:
{
path: '/some-path-to-compare`,
}
然后,使用loop,然后与路径
字段进行比较,而不是按很多行进行比较。您可以将所有路径放入路径数组,然后运行indexOf()函数以查看是否适合
const path=['/'、'/path'、'/path1']
常量路径=“/”,
如果(路径indexOf(路径)>=0){
console.log('路径存在')
}否则{
console.log('路径不存在')
}
使用includes()
,如果值在数组中,它将返回true或false
const路径名=[
'/',
“/kurikulum/”,
“/pengembangan diri/”,
“/statistik/”,
“/teknologi/”,
“/ekonomi/”,
“/desain/”,
“/corona/”
]
if(路径名.includes(location.pathname)){
//做点什么
}
您可以使用Array.includes
检查给定数组中是否存在当前路径名
let pathArr=['/'、'/kurikulum/'、'/pengembangan diri/'、'/statistik/'、'/teknologi/'、'/ekonomi/'、'/desain/'、'/corona/'];
设testPath='/desain/';
if(路径包含(测试路径)){
write('path found!');
};代码>另一种方法是可以使用array.filter或array.some
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const searchFunc = (searchItem) => words.filter(word => word === searchItem).length > 0;
if(searchFunc('limit')){
console.log("Item is found");
}
// expected output: "Item is found"
如果我们想反过来呢?像现在在数组中的/path/
?@MuhZulzidan你打算在这里做什么?我不明白。