You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

优化JavaScript路径检测函数:简化重复判断逻辑

优化方案

方案一:使用数组 + includes() 方法

把需要排除的路径统一放到数组里,利用数组的includes()方法判断当前路径是否在排除列表中,代码更简洁且易维护——后续要新增/删除排除路径,直接修改数组即可。

function checkPathName() {
  const excludedPaths = [
    '/groovybaby-/241315',
    '/cleopatra/241162',
    '/cumulus/528678'
  ];
  return !excludedPaths.includes(window.location.pathname);
}

checkPathName();

方案二:使用Set(适合大量排除路径场景)

如果后续需要排除的路径数量较多,Set的has()方法查找性能比数组includes()更优,适合高频调用的场景:

function checkPathName() {
  const excludedPaths = new Set([
    '/groovybaby-/241315',
    '/cleopatra/241162',
    '/cumulus/528678'
  ]);
  return !excludedPaths.has(window.location.pathname);
}

checkPathName();

额外优化:抽离排除路径到函数外部

如果这个排除列表在其他地方也会用到,可以把它抽到函数外面,避免每次调用函数都重复创建数组/Set:

// 抽离到外部,作为全局常量或模块导出
const EXCLUDED_PATHS = [
  '/groovybaby-/241315',
  '/cleopatra/241162',
  '/cumulus/528678'
];

function checkPathName() {
  return !EXCLUDED_PATHS.includes(window.location.pathname);
}

checkPathName();

内容的提问来源于stack exchange,提问作者PattRana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:55:29