我知道有这样一个问题,但是我的有点不同,它已经可以工作了,但是我不知道如何简化它。 if (location.pathname === `/` || location.pathname ===`/kurikulum/` || location.pathname === `/pengembangan-diri/` || location.pathname === `/statistik/` || location.pathname === `/teknologi/` || location.pathname === `/ekonomi/` || location.pathname === `/desain/` || location.pathname === `/corona/`)
如您所见,它并不漂亮,我想知道我们能不重复 location.pathname
吗?
这是在 Gatsby 上,但这是一个JavaScript问题
最佳答案
您可以使用Array.includes
来检查当前路径名是否存在于给定的数组中。
let pathArr = ['/', '/kurikulum/', '/pengembangan-diri/', '/statistik/', '/teknologi/', '/ekonomi/', '/desain/', '/corona/'];
let testPath = '/desain/';
if (pathArr.includes(testPath)) {
document.write('path found!');
};
在此处了解有关
Array.includes
的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
关于javascript - javascript中的if语句中的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62724466/