javascript - javascript中的if语句中的多个条件

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

最佳答案

您可以使用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/

相关文章:

javascript - 如何安排动态创建的 Canvas ?

javascript - Nuxt 页面作为组件?

javascript - Angular 2 中的时间倒计时

javascript - 在 <ul> 中隐藏 <li> 元素

javascript - 为什么请求接受: */* when the browser is asking for a javascript file?

javascript - React 子组件不会在父状态更改时重新渲染

javascript - 为什么我不能使用 rxjs 通过 .map 映射我的数组

javascript - 如果输入字段的值 = 瑞典,则需要选中一个复选框

javascript - Vue 不更新全局 $prototype 变量

javascript - 获取点击文本的字体颜色?