javascript - 带有 include() 的 url 检查器
问题描述
我正在尝试用 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?
解决方案
这里的问题是它同时{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
语句的语句,因为 a 有一些特殊性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 发布了相同的解决方案。
推荐阅读
- android - 在 Android 10 及更高版本中使用 MediaStore 保存图像后获取图像信息
- javascript - 来自 firebase 的数据正在以洗牌的方式出现?
- github - 无法在 github 上上传客户端部分
- scala - 无法对 Apache Flink 实例运行远程任务
- c++ - 从单元掩码中查找所有逻辑驱动器
- database - 根据 Laravel 的身份验证方法连接到不同的数据库
- java - 如何验证 oracle 原始列的条目
- wpf - 如何设置 RadioButton.IsChecked,如果它的内容获得焦点
- javascript - 首先按位 OR '|' 拆分字符串 然后通过逻辑 OR '||' 在jQuery中
- asp.net-web-api - SignalR 突然死亡 - 500 内部服务器错误