简体   繁体   English

javascript中的Boolean对象为“false”参数返回true

[英]Boolean object in javascript returns true for “false” parameter

I have a little problem. 我有一点问题。

I have situations where my ajax calss returns a string. 我的情况是我的ajax calss返回一个字符串。

sometimes that string is "false" i want to always convert that string value into a boolean i tried : new Boolean(thatValue) 有时该字符串是“假”我想总是将该字符串值转换为我尝试过的布尔值:new Boolean(thatValue)

but it returns true even for "false" as a paremter 但即使是作为一个paremter的“假”,它也会返回true

is there anyway to solve this? 无论如何要解决这个问题? except me writing my own custom function that will return false if "flase" ?.. 除了我写自己的自定义函数,如果“flase”会返回false?

thank you 谢谢

The best way to do this you've already described: 你已经描述过这样做的最佳方法:

if(value === 'true') {
  //do something
}

Or: 要么:

if(value !== 'false') {
  //do something
}

You're limited by JavaScript's weak typing here, actually working to your disadvantage, where any non-empty string will convert to a true boolean, even if that string is "false" . 你受限于JavaScript的弱类型,实际上你的劣势,即使该字符串为"false" ,任何非空字符串都将转换为true布尔值。

To get it and store it for use elsewhere, something like this works: 要获得它并将其存储在其他地方使用,这样的工作:

var myBool = value !== "false";

A string is always true if it contains some text, even if that text is "false". 如果字符串包含一些文本,则该字符串始终为true,即使该文本为“false”。 You can check for it using the ternary operator: 您可以使用三元运算符检查它:

thatValue == "false" ? false : true

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

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