如何在JavaScript中将字符串转换为布尔值

如何在JavaScript中将字符串转换为布尔值

本文介绍了如何在JavaScript中将字符串转换为布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将表示布尔值的字符串(例如'true','false')转换为JavaScript中的内在类型吗?



我有一个隐藏的表单在HTML中,根据用户在列表中的选择进行更新。此表单包含一些表示布尔值的字段,并使用内部布尔值进行动态填充。但是,一旦将此值放入隐藏的输入字段,它就会变成一个字符串。



一旦转换为字段,我就能找到确定字段的布尔值的唯一方法一个字符串,取决于其字符串表示的字面值。

  var myValue = document.myForm.IS_TRUE.value; 
var isTrueSet = myValue =='true';

有没有更好的方法来实现这个目标?



  var isTrueSet =(myValue =='true') ; 

你可以通过使用身份运算符使其更加严格( === ),当比较变量具有不同类型时,它不会进行任何隐式类型转换,而不是相等运算符( == )。

  var isTrueSet =(myValue ==='true'); 






不要:



您应该谨慎使用这两种方法以满足您的特定需求:

  var myBool = Boolean(false); // == true 

var myBool = !!false; // == true

任何非空字符串的字符串都将计算为 true 使用它们。虽然它们是我能想到的关于布尔转换的最干净的方法,但我认为它们不是你想要的。


Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?

I have a hidden form in HTML that is updated based upon 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?

解决方案

Do:

var isTrueSet = (myValue == 'true');

You could make it stricter by using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types, instead of the equality operator (==).

var isTrueSet = (myValue === 'true');


Don't:

You should probably be cautious about using these two methods for your specific needs:

var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true

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.

这篇关于如何在JavaScript中将字符串转换为布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:20