在 JavaScript 函数中返回布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7770187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning a boolean value in a JavaScript function
提问by tryurbest
I am doing a client side form validation to check if passwords match. But the validation function always returns undefined
.
我正在进行客户端表单验证以检查密码是否匹配。但是验证函数总是返回undefined
.
function validatePassword(errorMessage)
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
if(password.value)
{
// Check if confirm_password matches
if(password.value != confirm_password.value)
{
return false;
}
}
else
{
// If password is empty but confirm password is not
if(confirm_password.value)
{
return false;
}
}
return true;
}
Please note that the validatePassword
is called from a member function of the Form object.
请注意,validatePassword
是从 Form 对象的成员函数调用的。
function Form(validation_fn)
{
// Do other stuff
this.submit_btn = document.getElementById("submit");
this.validation_fn = validation_fn;
}
Form.prototype.submit = funciton()
{
var result;
if(this.validation_fn)
{
result = this.validation_fn();
}
//result is always undefined
if(result)
{
//do other stuff
}
}
采纳答案by pimvdb
You could simplify this a lot:
你可以简化很多:
- Check whether one is not empty
- Check whether they are equal
- 检查一个是否为空
- 检查它们是否相等
This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:
这将导致这个,它总是返回一个布尔值。你的函数也应该总是返回一个布尔值,但是如果你简化你的代码,你会发现它会做得更好:
function validatePassword()
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
return password.value !== "" && password.value === confirm_password.value;
// not empty and equal
}
回答by Sunny Patel
You could wrap your return value in the Boolean function
您可以将返回值包装在布尔函数中
Boolean([return value])
That'll ensure all falsey values are false and truthy statements are true.
这将确保所有 falsey 值都是 false 并且 true 陈述是 true。