javascript中if语句中的多个条件

Muh*_*dan 2 javascript

我知道有这样的问题,但我的有点不同,它已经有效,但我不知道如何简化它。

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 问题

ris*_*211 5

您可以使用Array.includes检查当前路径名是否存在于给定数组中。

let pathArr = ['/', '/kurikulum/', '/pengembangan-diri/', '/statistik/', '/teknologi/', '/ekonomi/', '/desain/', '/corona/'];
let testPath = '/desain/';

if (pathArr.includes(testPath)) {
   document.write('path found!');
};
Run Code Online (Sandbox Code Playgroud)

Array.includes在此处了解更多信息:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes