How do I compare string and boolean in Javascript?

一笑奈何 提交于 2019-12-22 01:54:54

问题


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.

So if I run (!data) whenever I want to check "false" == false then they not worked.

So how can I parse bool from String in JavaScript then?

"true" == true and "false" == false. Then the code (!data) can check what it is [true and false]


回答1:


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.




回答2:


"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



回答3:


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

This works fine.




回答4:


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.




回答5:


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.




回答6:


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 }




回答7:


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




回答8:


if(data+''=='true'){
    alert('true');
}  

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



来源:https://stackoverflow.com/questions/5659085/how-do-i-compare-string-and-boolean-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!