【问题标题】:Javascript - comparing loaction.pathname not working as expected with or operatorJavascript - 比较 loaction.pathname 与 or 运算符没有按预期工作
【发布时间】:2021-05-16 15:54:22
【问题描述】:

我正在尝试获取当前页面的 loacation.pathname 并比较它以查看它的 /Login 或 /Register,如果它是其中之一,则不应执行 if 中的代码。

代码:

if (location.pathname != '/Login' || location.pathname != '/Register')
     {
       prevView.push(location.href); // Add View to PreviousView so when needed we can navigate back to previous Page/View
       prevView.shift(); // Remove the First element from the array
     }

我也试过了:

if ((location.pathname != '/Login') || (location.pathname != '/Register')

 if (((location.pathname != '/Login') || (location.pathname != '/Register')))

但不工作 - 我做错了什么。

【问题讨论】:

  • 查看布尔逻辑。你需要&&,而不是||
  • 您能否通过登录控制台检查 location.pathname 的值?

标签: javascript if-statement compare


【解决方案1】:

您使用的是||,因此它总是会失败。 你必须使用&&

if (location.pathname != '/Login' && location.pathname != '/Register')

让我用人类语言来分解它。 如果我的位置路径名等于 /login 或我的位置路径名等于 /register,我希望你做点什么。 (== 变体)

但是....

(现在出现了“不是”变体,即您正在使用的变体)如果我的位置路径名不等于 /login... 哦等等,确实如此!所以“返回”值是假的!让我们继续我的另一个陈述......或者它不等于 /register,这是真的!进入这段代码!

【讨论】:

  • 多么愚蠢的错误 - 现在可以了,谢谢
  • @Stefan27 发生在我们当中。如果答案是正确的,请接受答案。祝你的编程冒险好运!
  • 我会 - 我需要等待 4 分钟才能接受。谢谢。
猜你喜欢
  • 2021-06-12
  • 2020-12-24
  • 1970-01-01
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多