繁体   English   中英

如何调试 JavaScript switch 语句错误?

[英]How to debug a JavaScript switch statement error?

我正在尝试创建一个函数,每次加载页面时都会运行一次。

该函数将检查用户所在的页面(url/路径),然后它将通过 switch 语句循环一次,如果任何路径名称匹配,它将向 API 发送一些信息。

我只收到“没有网址/路径名称匹配”。 我知道我几乎有了正确的解决方案。

<script>    
function winLocation(path) {
return window.location.pathname.indexOf(path);
}
console.log(winLocation);
switch (true) {
case winLocation("stack"):
    console.log('This is a stack overflow page');
    // Fire info to api
    break;
case winLocation("google"):
    // Fire info to api if url has google in it
    break;
default:
    console.log("no urls/path names match");
};
</script>

https://codepen.io/bkdigital/pen/eQYQPL - Codepen 代码示例

如果要检查整个 url,则需要在函数中使用href而不是pathname

 window.location.href.indexOf(path)

此外,由于您在 switch 中使用了true ,因此winLocation的响应winLocation应该是一个布尔值,您可以通过检查它是否与 -1 不同来实现。

function winLocation(path) {
   return window.location.href.indexOf(path) !== -1;
}

那会给你你想要的结果。

要检查它,只需运行下面的代码片段:

 function winLocation(path) { return window.location.href.indexOf(path) !== -1; } switch (true) { case winLocation("stack"): console.log('This is a stack overflow page'); // Fire info to api break; case winLocation("google"): console.log('This is a google page'); // Fire info to api if url has google in it break; default: console.log("no urls/path names match"); };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM