如何在 JavaScript 中将字符串转换为布尔值?
我可以将表示布尔值(例如“true”、“false”)的字符串转换为 JavaScript 中的内在类型吗?
我有一个 HTML 格式的隐藏表单,该表单根据用户在列表中的选择进行更新。 此表单包含一些表示布尔值的字段,并动态填充内在布尔值。 但是,一旦将该值放入隐藏输入字段,它就会变成字符串。
一旦将字段转换为字符串,我找到确定字段布尔值的唯一方法是依赖于其字符串表示形式的文字值。
var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
有更好的方法来实现这一点吗?
Can I convert a string representing a boolean value (e.g., 'true', 'false') into an intrinsic type in JavaScript?
I have a hidden form in HTML that is updated based on a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.
The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.
var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
Is there a better way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
使用 JSON 解析的通用解决方案:
更新(没有 JSON):
我还创建了小提琴来测试它 http://jsfiddle.net/remunda/2GRhG/
Universal solution with JSON parse:
UPDATE (without JSON):
I also created fiddle to test it http://jsfiddle.net/remunda/2GRhG/
你的解决方案很好。
在这种情况下,使用
===
会很愚蠢,因为字段的value
将始终是String
。Your solution is fine.
Using
===
would just be silly in this case, as the field'svalue
will always be aString
.布尔对象没有“解析”方法。
Boolean('false')
返回 true,所以这不起作用。!!'false'
也会返回true
,所以这也不起作用。如果您希望字符串
'true'
返回布尔值true
和字符串'false'
返回布尔值false
,那么最简单的解决方案是使用eval()
。eval('true')
返回 true,eval('false')
返回 false。使用
eval()
时请记住性能和安全影响。The Boolean object doesn't have a 'parse' method.
Boolean('false')
returns true, so that won't work.!!'false'
also returnstrue
, so that won't work also.If you want string
'true'
to return booleantrue
and string'false'
to return booleanfalse
, then the simplest solution is to useeval()
.eval('true')
returns true andeval('false')
returns false.Keep in mind the performance and security implications when using
eval()
though.这将为每个假值返回
false
,为每个真值返回true
('false'
、'f'
除外) 、'no'
、'n'
和'0'
(不区分大小写)。This returns
false
for every falsy value andtrue
for every truthy value except for'false'
,'f'
,'no'
,'n'
, and'0'
(case-insensitive).答案有很多,很难选出一个。 就我而言,我在选择时会优先考虑性能,因此我创建了 这个 jsPerf 我希望它能带来一些启发这里。
结果简介(越高越好):
它们是链接的到相关的答案,您可以在其中找到有关每个答案的更多信息(优点和缺点); 特别是在评论中。
There are a lot of answers and it's hard to pick one. In my case, I prioritise the performance when choosing, so I create this jsPerf that I hope can throw some light here.
Brief of results (the higher the better):
They are linked to the related answer where you can find more information (pros and cons) about each one; specially in the comments.
这是取自已接受的答案,但实际上它有一个非常薄弱的点,我很惊讶它是如何获得这么多赞成票的,问题是你必须考虑字符串的大小写,因为这是区分大小写的
This has been taken from the accepted answer, but really it has a very weak point, and I am shocked how it got that count of upvotes, the problem with it that you have to consider the case of the string because this is case sensitive
我使用以下内容:
此函数执行通常的布尔强制转换,但字符串“false”(不区分大小写)和“0”除外。
I use the following:
This function performs the usual Boolean coercion with the exception of the strings "false" (case insensitive) and "0".
最简单的解决方案
Simplest solution ????????
with ES6+
use the logical NOT twice [ !! ] to get the string converted
Just paste this expression...
And pass your string to it!
???????? Bonus! ????????
You can include other strings at will to easily extend the usage of this expression...:
您要查找的表达式就像
This
tests
myValue
against a Regular expression 一样,不区分大小写,并且不会修改原型。例子:
The expression you're looking for simply is
as in
This tests
myValue
against a regular expression , case-insensitive, and doesn't modify the prototype.Examples:
您可以使用
JSON.parse
如下:在这种情况下
.toLowerCase
很重要you can use
JSON.parse
as follows:in this case
.toLowerCase
is important已经有很多答案了。 但以下内容在某些情况下可能很有用。
这在具有非布尔值的示例中非常有用。
There are already so many answers available. But following can be useful in some scenarios.
This can be useful where one examples with non-boolean values.
我很惊讶没有建议
includes
您可以修改 true 检查或包含更多条件(例如
null
、''
)。I'm suprised that
includes
was not suggestedYou can modify the check for truely or include more conditions (e.g.
null
,''
).将 string("true", "false") 和 boolean 转换为 boolean
其中
flag
可以是To convert both string("true", "false") and boolean to boolean
Where
flag
can be该函数可以处理字符串以及布尔值真/假。
演示如下:
This function can handle string as well as Boolean true/false.
Demonstration below:
One Liner
我们只需要考虑“false”字符串,因为任何其他字符串(包括“true”)都已经是
true
。测试
更详尽的版本
测试
One Liner
We just need to account for the "false" string since any other string (including "true") is already
true
.Test
A more exaustive version
Test
我正在用这个
I'm using this one
你为什么不尝试这样的事情
当给出一些其他文本而不是 true 或 false 时,无论大小写,它都会返回一个错误,并且它也会捕获数字
why don't you try something like this
It will return an error when some other text is given rather than true or false regardless of the case and it will capture the numbers also as
您需要(在您的思考中)将您的选择的值和该值的表示分开。
在 JavaScript 逻辑中选择一个需要从字符串哨兵转换到本机类型的点,并在那里进行比较,最好只对每个需要转换的值进行一次比较。 请记住解决如果字符串哨兵不是脚本所知道的字符串(即您默认为 true 还是 false?)时需要发生的情况,
换句话说,是的,您需要依赖于字符串的值。 :-)
You need to separate (in your thinking) the value of your selections and the representation of that value.
Pick a point in the JavaScript logic where they need to transition from string sentinels to native type and do a comparison there, preferably where it only gets done once for each value that needs to be converted. Remember to address what needs to happen if the string sentinel is not one the script knows (i.e. do you default to true or to false?)
In other words, yes, you need to depend on the string's value. :-)
另一个解决方案。 jsFiddle
测试用例在节点中运行
another solution. jsFiddle
test cases run in node
毫无疑问,最简单的方法(假设您的字符串为“true”或“false”)是:
始终对这些使用 === 运算符而不是 == 运算符转换类型!
Hands down the easiest way (assuming you string will be 'true' or 'false') is:
Always use the === operator instead of the == operator for these types of conversions!
做法:
使用恒等运算符 (
===
),当比较的变量具有不同类型时,它不会进行任何隐式类型转换。如果字符串为“true”,则将
isTrueSet
设置为布尔值true
;如果字符串为“false”或未设置,则将设置为布尔值false
全部。为了使其不区分大小写,请尝试:
不要:
您可能应该谨慎使用这两种方法来满足您的特定需求:
任何不是空字符串的字符串都将计算为
true
通过使用它们。 尽管它们是我能想到的关于布尔转换的最干净的方法,但我认为它们不是您正在寻找的。Do:
using the identity operator (
===
), which doesn't make any implicit type conversions when the compared variables have different types.This will set
isTrueSet
to a booleantrue
if the string is "true" and booleanfalse
if it is string "false" or not set at all.For making it case-insensitive, try:
Don't:
You should probably be cautious about using these two methods for your specific needs:
Any string which isn't the empty string will evaluate to
true
by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.警告
这个高度赞扬的遗留答案在技术上是正确的,但仅涵盖非常具体的场景,即当您的字符串值恰好是
"true"
或"false"
时。传递到下面这些函数的无效 json 字符串将引发异常。
原答案:
怎么样?
或使用 jQuery
Warning
This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY
"true"
or"false"
.An invalid json string passed into these functions below WILL throw an exception.
Original answer:
How about?
or with jQuery
我认为这更通用:
if (String(a).toLowerCase() == "true")
...它是:
I think this is much more universal:
if (String(a).toLowerCase() == "true")
...It goes:
记住要匹配大小写:
另外,如果是表单元素复选框,还可以检测该复选框是否被选中:
假设如果被选中,则“set”等于true。 这评估为真/假。
Remember to match case:
Also, if it's a form element checkbox, you can also detect if the checkbox is checked:
Assuming that if it is checked, it is "set" equal to true. This evaluates as true/false.
这是我最近遇到的进行布尔转换的最简单方法。 想到了添加一下。
This is the easiest way to do boolean conversion I came across recently. Thought of adding it.
您可以使用正则表达式:
如果您喜欢扩展 String 类,您可以这样做:
对于那些想要扩展 String 对象来获取此对象但担心可枚举性并担心与扩展的其他代码发生冲突的人(请参阅注释) String 对象:(
当然在旧版浏览器中不起作用,Firefox 显示 false,而 Opera、Chrome、Safari 和 IE 显示 true。错误 720760)
You can use regular expressions:
If you like extending the String class you can do:
For those (see the comments) that would like to extend the String object to get this but are worried about enumerability and are worried about clashing with other code that extends the String object:
(Won't work in older browsers of course and Firefox shows false while Opera, Chrome, Safari and IE show true. Bug 720760)
木眼要小心。
在看到获得 500 多个赞成票的最佳答案后的后果后,我觉得有必要发布一些实际上有用的东西:
让我们从最短但非常严格的方法开始:
并以适当的、更宽容的方法结束:
测试:
Wood-eye be careful.
After seeing the consequences after applying the top answer with 500+ upvotes, I feel obligated to post something that is actually useful:
Let's start with the shortest, but very strict way:
And end with a proper, more tolerant way:
Testing:
我认为 @Steven 的答案是最好的,并且比传入值只是一个字符串处理更多的情况。 我想稍微扩展一下并提供以下内容:
如果您已经知道必须考虑的所有
true
情况,则无需涵盖所有false
情况为了。 您可以将任何可以传递true
值的内容传递到此方法中(或添加其他值,这非常简单),其他所有内容都将被视为false
I thought that @Steven 's answer was the best one, and took care of a lot more cases than if the incoming value was just a string. I wanted to extend it a bit and offer the following:
It's not necessary to cover all the
false
cases if you already know all of thetrue
cases you'd have to account for. You can pass anything into this method that could pass for atrue
value (or add others, it's pretty straightforward), and everything else would be consideredfalse