为什么我不正确的 if 语句有效?
Why did my incorrect if statement work?
我最近遇到了以下语法错误:
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 的早期尝试过这种 shorthand 并很快发现它 没有 工作。
无论如何,我已经更正了代码,但我不明白它为什么起作用,这让我很烦。
谁能解开这个谜团?
您的字符串是表示真值的表达式。
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"
当然会有效,而且它会一直有效因为你的条件会总是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 (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 的早期尝试过这种 shorthand 并很快发现它 没有 工作。
无论如何,我已经更正了代码,但我不明白它为什么起作用,这让我很烦。
谁能解开这个谜团?
您的字符串是表示真值的表达式。
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"
当然会有效,而且它会一直有效因为你的条件会总是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);
}