JavaScript: Parsing a string Boolean value?

This question already has an answer here:

  • How can I convert a string to boolean in JavaScript? 71 answers

  • I would be inclined to do a one liner with a ternary if.

    var bool_value = value == "true" ? true : false
    

    Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:

    var bool_value = value == 'true';
    

    This works because value == 'true' is evaluated based on whether the value variable is a string of 'true' . If it is, that whole expression becomes true and if not, it becomes false , then that result gets assigned to bool_value after evaluation.


    你可以使用JSON.parse:

    JSON.parse("true"); //returns boolean true
    

    It depends how you wish the function to work.

    If all you wish to do is test for the word 'true' inside the string, and define any string (or nonstring) that doesn't have it as false, the easiest way is probably this:

    function parseBoolean(str) {
      return /true/i.test(str);
    }
    

    If you wish to assure that the entire string is the word true you could do this:

    function parseBoolean(str) {
      return /^true$/i.test(str);
    }
    
    链接地址: http://www.djcxy.com/p/75066.html

    上一篇: 在javascript中将字符串转换为布尔值

    下一篇: JavaScript:解析一个字符串布尔值?