Javascript 在javascript中将字符串转换为布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4344542/
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
Convert string to Boolean in javascript
提问by user137348
How to convert a string to Boolean ?
如何将字符串转换为布尔值?
I tried using the constructor Boolean("false"), but it's always true.
我尝试使用构造函数Boolean("false"),但它总是正确的。
回答by Aistina
I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval... which you don't).
我会在这里使用一个简单的字符串比较,据我所知,没有内置函数可以用于您想做的事情(除非您想诉诸eval......而您不想这样做)。
var myBool = myString == "true";
回答by iamwhitebox
I would like to answer this to improve upon the accepted answer.
我想回答这个问题以改进已接受的答案。
To improve performance, and in real world cases where form inputs might be passing values like 'true', or 'false', this method will produce the best results.
为了提高性能,在实际情况下,表单输入可能会传递诸如“真”或“假”之类的值,此方法将产生最佳结果。
function stringToBool(val) {
return (val + '').toLowerCase() === 'true';
}
JSPerf
JSPerf


回答by Rohith Yeravothula
you can also use JSON.parse() function
你也可以使用 JSON.parse() 函数
JSON.parse("true") returns true (Boolean)
JSON.parse("true") 返回 true(布尔值)
JSON.parse("false") return false (Boolean)
JSON.parse("false") 返回 false(布尔值)
回答by Arun Chandran C
Actually you don't get the meaning of Boolean method.It always return true if the variable is not null or empty.
其实你没有理解布尔方法的含义。如果变量不为空或不为空,它总是返回true。
var variable = some value;
Boolean(variable);
var variable = some value;
Boolean(variable);
If my variable have some value then it will
return trueelse
return falseYou can't use Boolean as you think.
如果我的变量有一些值,那么它会
return true否则
return false你不能像你想象的那样使用布尔值。
回答by Sandeep
trick string to boolean conversion in javascript. e.g.
在javascript中将字符串转换为布尔值。例如
var bool= "true";
console.log(bool==true) //false
var bool_con = JSON.parse(bool);
console.log(bool_con==true) //true
回答by Eugen Mihailescu
I am still amazed how people vote blindly for solutions that won't work, like:
我仍然感到惊讶的是人们如何盲目地投票支持行不通的解决方案,例如:
var myBool = myString == "true";
The above is so BUGGY!!!
上面太BUGGY了!!!
Not convinced? Just try myString = true (I mean the boolean true). What is the evaluation now? Opps: false!
不服气?只需尝试 myString = true (我的意思是布尔值 true)。现在评价如何?欧普:假的!
Alternative
选择
var myString=X; // X={true|false|"true"|"false"|"whatever"}
myString=String(myString)=='true';
console.log(myString); // plug any value into X and check me!
will always evaluate right!
永远评价正确!
回答by David M?rtensson
Depends on what you see as false in a string.
取决于您在字符串中看到的错误内容。
Empty string, the word false, 0, should all those be false or is only empty false or only the word false.
空字符串,单词false,0,应该所有这些都是false还是空的false或只有false这个词。
You probably need to buid your own method to test the string and return true or false to be 100 % sure that it does what you need.
您可能需要构建自己的方法来测试字符串并返回 true 或 false 以 100% 确定它可以满足您的需求。
回答by Wesley Gon?alves
I believe the following code will do the work.
我相信以下代码可以完成这项工作。
function isBoolean(foo) {
if((foo + "") == 'true' || (foo + "") == 'false') {
foo = (foo + "") == 'true';
} else {
console.log("The variable does not have a boolean value.");
return;
}
return foo;
}
Explaining the code:
解释代码:
foo + ""
converts the variable 'foo' to a string so if it is already boolean the function will not return an invalid result.
将变量 'foo' 转换为字符串,因此如果它已经是布尔值,该函数将不会返回无效结果。
(foo + "") == 'true'
This comparison will return true only if 'foo' is equal to 'true' or true (string or boolean). Note that it is case-sensitive so 'True' or any other variation will result in false.
仅当 'foo' 等于 'true' 或 true(字符串或布尔值)时,此比较才会返回 true。请注意,它区分大小写,因此 'True' 或任何其他变体将导致错误。
(foo + "") == 'true' || (foo + "") == 'false'
Similarly, the sentence above will result in true only if the variable 'foo' is equal to 'true', true, 'false' or false. So any other value like 'test' will return false and then it will not run the code inside the 'if' statement. This makes sure that only boolean values (string or not) will be considered.
同样,仅当变量“foo”等于“true”、“true”、“false”或“false”时,上面的句子才会导致 true。因此,任何其他值(如“test”)都将返回 false,然后它不会运行“if”语句中的代码。这确保只考虑布尔值(字符串与否)。
In the 3rd line, the value of 'foo' is finally "converted" to boolean.
在第三行,'foo' 的值最终被“转换”为布尔值。
回答by Felipe Marques
These lines give the following output:
这些行提供以下输出:
Boolean(1).toString(); // true
Boolean(0).toString(); // false
回答by Free Consulting
javascript:var string="false";alert(Boolean(string)?'FAIL':'WIN')
will not work because any non-empty string is true
将不起作用,因为任何非空字符串是 true
javascript:var string="false";alert(string!=false.toString()?'FAIL':'WIN')
works because compared with string represenation
有效,因为与字符串表示相比

