【问题标题】:url checker with includes()带有 include() 的 url 检查器
【发布时间】:2021-12-18 02:22:34
【问题描述】:

我正在尝试用 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
    }
}

我正在使用的网址是 {example.com}/account/profiles/mylist,当我测试 /mylist 时,它会保留显示“查看帐户...” 我可以更改什么以使 /account 不干扰 /mylist?

【问题讨论】:

  • "当我测试 /mylist 时,它一直显示“正在查看帐户...”" 这与您的预期有何不同?文字第一个条件满足包含/account 的定义。如果您需要知道 URL 以什么结尾,为什么不使用恰当命名的 endsWith() 方法...?

标签: javascript typescript path include


【解决方案1】:

为什么不改用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)已过时并且难以阅读/维护(考虑到每个条件都需要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...";
}

【讨论】:

    【解决方案2】:

    这里的问题是{example.com}/account/profiles/mylist 包含both 字符串"/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;
    }

    全面披露——我正在输入此编辑esqew posted the same solution。

    【讨论】:

      猜你喜欢
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 2019-12-07
      • 1970-01-01
      • 2012-09-02
      • 2017-10-23
      • 1970-01-01
      相关资源
      最近更新 更多