How do I compare string and boolean in Javascript?

后端 未结 9 1250
长情又很酷
长情又很酷 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:50

    If its just a json "false"/"true", you can use,

    if(! eval(data)){
        // Case when false
    }
    

    It would be more cleaner, if you restrict the code to accept only JSON data from server, and always jsonParse or eval it to JS object (something like jquery getJSON does. It accepts only JSON responses and parse it to object before passing to callback function).

    That way you'll not only get boolean as boolean-from-server, but it will retain all other datatypes as well, and you can then go for routine expressions statements rather than special ones.

    Happy Coding.

    0 讨论(0)
  • 2020-12-11 01:50
    if(data+''=='true'){
        alert('true');
    }  
    

    Convert boolean to string by appending with blank string. and then compare with Stringobject.

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

    Try expression data == "true"

    Tests:

    data = "false" -- value will be false

    date = "true" -- value will be true

    Also, fix your JSON. JSON can handle booleans just fine.

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