【问题标题】:Why did my incorrect if statement work?为什么我不正确的 if 语句有效?
【发布时间】:2015-03-17 09:41:59
【问题描述】:

我最近遇到了以下语法错误:

if (button=="init" || "show_selected" || "show_all") {

当然应该是这样的:

if (button=="init" || button=="show_selected" || button=="show_all") {

但是,最初的声明似乎在 Chrome、FF 和 IE9 中完美运行!?!?我只是在添加新选项时偶然发现了我的错误。

为了澄清,“init”、“show_selected”和“show_all”是调用函数时使用的字符串参数;例如

onclick=myFunction("init");

我确定我记得我很早就在学习 JS 时尝试过这种速记,但很快发现它没有奏效。

无论如何,我已经更正了代码,但让我很恼火的是,我看不出它为什么工作。

谁能解开这个谜?

【问题讨论】:

  • 嗯,它没有“完美”地工作,因为逻辑不正确,但它肯定不是语法错误。
  • || "show_selected" 永远为真
  • "show_all" 被强制转换为布尔值 true

标签: javascript if-statement syntax-error logical-operators


【解决方案1】:

当然会起作用,而且会一直起作用,因为您的状态会一直是true

if (button=="init" || "show_selected" || "show_all")

将始终为真,因为 "show_selected" 是一个字符串,如果您将其作为 if 语句条件传递,它将始终为真,您的代码将按如下方式评估:

if (button=="init" || true || true) // Will always be true

因为写if ("show_all") 等价于if ("show_all" !== null) 也就是true

例如,试试这个:

if ("show_all"){ //returns true (the statement is true)
   alert(true); 
}

【讨论】:

  • 谢谢,现在说得通了。我已经放入了 if 语句,假设我最终会添加不会使用该部分功能的选项。事实证明,到目前为止,所有选项都使用该代码,这就是我没有注意到问题的原因。
【解决方案2】:

你的字符串是真值的表达式。

if ("show_selected") { /* ... */ }

... 将运行块中的代码。

您在每个 OR 语句的 RHS 上都使用了字符串,因此每个 OR 语句的 RHS 都是正确的。


给定:

myFunction("init");

然后:

button=="init"

是:

true

所以:

button=="init" || "show_selected" 
true || "show_selected" 
true

如果你要传入任何其他值

button=="init" || "show_selected" 
false || "show_selected" 
"show_selected" 

【讨论】:

    猜你喜欢
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多