【问题标题】:How to debug a JavaScript switch statement error?如何调试 JavaScript switch 语句错误?
【发布时间】:2019-04-07 18:35:03
【问题描述】:

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

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

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

<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 代码示例

【问题讨论】:

  • 为什么要使用开关?这看起来应该使用if/else 语句来完成。还有什么错误?
  • 您收到的错误信息是什么?
  • 这不是正确的语法,你的开关直接在你不能在这样的 iife 表达式中拥有的函数之外
  • 回答您的问题:在 javascript 中调试任何东西(只要它在前端)的最简单方法是使用浏览器中的 javascript 调试工具。它通常在您按 f12 时可用,并允许您在代码中设置断点并逐步跟踪它。
  • 您检查过indexOf 返回的内容吗?

标签: javascript if-statement url switch-statement


【解决方案1】:

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

 window.location.href.indexOf(path)

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

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

这会给你想要的结果。

要查看它,只需运行下面的代码 sn-p:

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");
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    相关资源
    最近更新 更多