bug^君 2008-11-05 00:13 采纳率: 25%
浏览 1238
已采纳

如何在 JavaScript 中将字符串转换为 boolean?

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?

转载于:https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript

  • 写回答

22条回答 默认 最新

  • 七度&光 2013-06-23 19:39
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(21条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog