简体   繁体   English

javascript:检查 boolean 值

[英]javascript : checking boolean values

I have a boolean value set as a hidden variable in the form and I have the below javascript.我有一个 boolean 值设置为表单中的隐藏变量,我有以下 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.我关心的显然是第三个 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我在 IE8 和 FF 4 中测试过

Suggestions are welcome.欢迎提出建议。

No, you don't have a boolean value in the hidden field.不,您在隐藏字段中没有 boolean 值。 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.当您像使用 boolean 值一样使用字符串值时,您会得到意想不到的结果。 A condition is false if the value is false , 0 , "" or null , but the string "false" is neither, so it's evaluated as true .如果值为false0""null ,则条件为 false ,但字符串"false"两者都不是,因此它被评估为true

If you want a boolean value, you have to parse the string.如果你想要一个 boolean 值,你必须解析字符串。 An easy way is to simply check if the string has a specific value:一种简单的方法是简单地检查字符串是否具有特定值:

var flag =  $('#popUpFlag').val() === 'true';

flag is a string, so have this instead: flag是一个字符串,所以用这个代替:

if (flag === "true") {
  //true
}
else if (flag === "false") {
  //false
}

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.嗯...我怀疑您使用的值是一个字符串,因此您在警报中正确地看到了该值,但当它试图像 boolean 一样查看它时却没有。

How can I convert a string to boolean in JavaScript? 如何在 JavaScript 中将字符串转换为 boolean?

Just try ocnverting to boolean and see if it still gives you the same issue只需尝试转换为 boolean 看看它是否仍然给您同样的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM