javascript:检查布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5800688/
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
javascript : checking boolean values
提问by Vinoth Kumar C M
I have a boolean value set as a hidden variable in the form and I have the below javascript .
我有一个布尔值设置为表单中的隐藏变量,我有下面的 javascript 。
$().ready(function() {
var flag = $('#popUpFlag').val();
alert("flag = "+flag);
if(flag){
alert("flag is true");
}else{
alert("flag is false");
}
})
These are the outputs for the alert .
这些是警报的输出。
flag =
flag is false
flag = false
flag is false
flag = true
flag is false
My concern is obviously the third output . When the flag is true , why is it printing "flag is false" , instead of "flag is true" . I tested it in IE8 and FF 4
我关心的显然是第三个输出。当 flag 为 true 时,为什么要打印 "flag is false" ,而不是 "flag is true" 。我在 IE8 和 FF 4 中测试过
Suggestions are welcome.
欢迎提出建议。
回答by Guffa
No, you don't have a boolean value in the hidden field. The value in the field is always a string.
不,您在隐藏字段中没有布尔值。该字段中的值始终是一个字符串。
When you use the string value as if it was a boolean value, you get unexpected results. A condition is false if the value is false
, 0
, ""
or null
, but the string "false"
is neither, so it's evaluated as true
.
当您像使用布尔值一样使用字符串值时,您会得到意想不到的结果。条件是假的,如果值是false
,0
,""
或null
,但是字符串"false"
两者都不是,所以它作为评价true
。
If you want a boolean value, you have to parse the string. An easy way is to simply check if the string has a specific value:
如果你想要一个布尔值,你必须解析字符串。一种简单的方法是简单地检查字符串是否具有特定值:
var flag = $('#popUpFlag').val() === 'true';
回答by Shadow Wizard is Ear For You
flag
is a string, so have this instead:
flag
是一个字符串,所以用这个代替:
if (flag === "true") {
//true
}
else if (flag === "false") {
//false
}
回答by Cyril Gupta
Hmm... I suspect that the value you are using is a string, so you're seeing the value correctly in the alert, but not when it tries to look at it like a boolean.
嗯...我怀疑您使用的值是一个字符串,所以您在警报中正确地看到了该值,但当它试图像布尔值一样查看它时则不然。
How can I convert a string to boolean in JavaScript?
Just try ocnverting to boolean and see if it still gives you the same issue
只需尝试转换为布尔值,看看它是否仍然给你同样的问题