How do I compare string and boolean in Javascript?

后端 未结 9 1249
长情又很酷
长情又很酷 2020-12-11 01:16

I got the Json \"false\" from server. I respond as bool but it\'s Json so it\'s in browser type is String instead of bool

相关标签:
9条回答
  • 2020-12-11 01:30

    To compare string and Boolean in JavaScript, let us see the following examples. It returns true:

    false == "0"; //true
    true == "1"; //true
    false == ""; //true
    

    The followings returns false:

    false == "false"; //false
    true == "true"; //false
    

    In addition, try the following example too:

    var data = true;
    data === "true" //false
    String(data) === "true" //true
    

    https://www.tutorialspoint.com/How-do-I-compare-String-and-Boolean-in-JavaScript

    0 讨论(0)
  • 2020-12-11 01:31
    var data = true;
    data === "true" //false
    String(data) === "true" //true
    

    This works fine.

    0 讨论(0)
  • 2020-12-11 01:31
    String.prototype.revalue= function(){
      if(/^(true|false|null|undefined|NaN)$/i.test(this)) return eval(this);
      if(parseFloat(this)+''== this) return parseFloat(this);
      return this;
    }
    

    From: http://www.webdeveloper.com/forum/showthread.php?t=147389

    Actually, you just need the first "if" statement from the function -- tests to find true or false in the code and the evals it, turning it into the boolean value

    0 讨论(0)
  • 2020-12-11 01:33

    I think you need to look at how the JSON data is being generated. You can definitely have a normal JS boolean false in JSON.

    { "value1" : false, "value2" : true }

    0 讨论(0)
  • 2020-12-11 01:44

    If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false. (from MDN Comparison Operators page)

    Examples:

    true == "true"; //false
    true == "1"; //true
    false == "false"; //false
    false == ""; //true
    false == "0"; //true
    
    0 讨论(0)
  • 2020-12-11 01:46

    I would just explicitly check for the string "true".

    let data = value === "true";
    

    Otherwise you could use JSON.parse() to convert it to a native JavaScript value, but it's a lot of overhead if you know it's only the strings "true" or "false" you will receive.

    0 讨论(0)
提交回复
热议问题