javascript javascript中的布尔对象为“false”参数返回true
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3343571/
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
Boolean object in javascript returns true for "false" parameter
提问by guy schaller
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
但即使将“false”作为参数,它也会返回 true
is there anyway to solve this? except me writing my own custom function that will return false if "flase" ?..
有没有办法解决这个问题?除了我编写自己的自定义函数,如果“flase”会返回 false ?..
thank you
谢谢
采纳答案by Nick Craver
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 trueboolean, even if that string is "false".
您在这里受到 JavaScript 弱类型的限制,实际上对您不利,任何非空字符串都将转换为true布尔值,即使该字符串是"false".
To get it and store it for use elsewhere, something like this works:
要获取它并将其存储以供其他地方使用,请执行以下操作:
var myBool = value !== "false";
回答by Karel Petranek
A string is always true if it contains some text, even if that text is "false". You can check for it using the ternary operator:
如果字符串包含某些文本,则它始终为真,即使该文本为“假”。您可以使用三元运算符检查它:
thatValue == "false" ? false : true

