url 带有 includes() 的检查器

url checker with includes()

我正在尝试用 js 制作一个 url 检查器,这是我遇到问题的代码部分:

switch (true) {
    case document.location.pathname.includes("/account"):
      presenceData.details = "Viewing account..."
    break
    case document.location.pathname.includes("/mylist"):
      presenceData.details = "Viewing list..."
    break
    }
}

我正在使用的 url 是 {example.com}/account/profiles/mylist 并且当我测试 /mylist 它一直显示“正在查看帐户...” 我可以更改什么以使 /account 不干扰 /mylist?

这里的问题是 {example.com}/account/profiles/mylist 包含 字符串 "/account""/mylist"。因此,当您遇到第一个案例时,就会进行匹配,然后您 break 退出开关。

let pathname = '/account/profiles/mylist';
switch (true) {
  case pathname.includes("/account"):
    console.log("Viewing account...");
    break;
  case pathname.includes("/mylist"):
    console.log("Viewing list...");
    break;
}

如果您知道 /mylist 在层次结构中总是处于更深的层次,在 /account 之下,您可以改变大小写的顺序:

let pathname = '/account/profiles/mylist';
switch (true) {
  case pathname.includes("/mylist"):
    console.log("Viewing list...");
    break;
  case pathname.includes("/account"):
    console.log("Viewing account...");
    break;
}

否则,您可能需要更细致的逻辑方法,并且您可能希望避免使用 switch 语句以支持 if/else 语句,因为 switch 有一些特殊性(具体来说,一旦满足一个案例,所有其他案例块将被解释为匹配,直到你 break)。

编辑:

或者,另一种选择是利用 endsWith 代替:

let pathname = '/account/profiles/mylist';
switch (true) {
  case pathname.endsWith("/account"):
    console.log("Viewing account...");
    break;
  case pathname.endsWith("/mylist"):
    console.log("Viewing list...");
    break;
}

完全披露 -- 当我输入此编辑时 .

为什么不使用 endsWith() 而不是...?

switch (true) {
    case document.location.pathname.endsWith("/account"):
      presenceData.details = "Viewing account..."
    break
    case document.location.pathname.endsWith("/mylist"):
      presenceData.details = "Viewing list..."
    break
    }
}

切线,但 switch 陈述(IMO)已经过时并且变得难以 read/maintain(考虑到 breaking 每个条件的必要性);此外,您对 switch (true) 的使用有点滥用 switch 的目的。无论如何,您可能应该简单地使用 if/else if 语句:

if (document.location.pathname.endsWith("/account")) {
    presenceData.details = "Viewing account...";
}
else (document.location.pathname.endsWith("/mylist")) {
    presenceData.details = "Viewing list...";
}