javascript是否在布尔表达式中使用优化? [英] Does javascript use optimization in boolean expressions?
问题描述
当我决定用经典的javascript构建普通的web表单验证时,我有一个奇怪的错误。输入文本字段有几个onblur处理程序和一个form-submit处理程序。
I have strange error when I decided to build ordinary web-form validation with classic javascript. There are several "onblur" handlers for input text fields and one "form-submit" handler.
当我这样使用它们时:
function loginCheck() {
... return true of false
}
function passwordCheck() {
...
}
function formValidation() {
return loginCheck() && passwordCheck();
}
它无法正常工作:passwordCheck从未调用过loginCheck失败了!
It doesn't work as I expect: "passwordCheck" never called if loginCheck is failed!
最后我有解决方法
function formValidation() {
ok = loginCheck();
ok &= passwordCheck();
return ok;
}
现在执行密码检查。但是当我选择:
Now password check is executed. But when I choose:
function formValidation() {
ok = loginCheck();
ok = ok && passwordCheck();
return ok;
}
如果loginCheck失败,则不会再次调用passwordCheck。
passwordCheck is never called again if loginCheck failed.
此外:loginCheck& passwordCheck返回布尔值,但& =运算符将其转换为0或1。 0对我的 onsubmit =return checkForm
处理程序不起作用。我必须再次将我的& =结果转换为布尔值:
Moreover: loginCheck & passwordCheck return boolean values, but &= operator covert it to "0" or "1". "0" doesn't work for my onsubmit="return checkForm"
handler. I have to convert my &= result to boolean once again:
function formValidation() {
ok = loginCheck();
ok &= passwordCheck();
return ok != 0;
}
这是javascript引擎的正常行为吗?
It is a normal behavior for javascript engines ?
推荐答案
是的,这很正常。它被称为短路评估,既方便又常见(即存在于很多语言(C,C ++,Java,Perl,许多其他语言),而不仅仅是JavaScript)。
Yes, it's normal. It's called a short-circuit evaluation and is both handy and very common (i.e. is present in a lot of languages (C, C++, Java, Perl, many others), not just JavaScript).
这篇关于javascript是否在布尔表达式中使用优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!