如何在 Javascript 中比较字符串和布尔值?

我从服务器获得了 Json "false".我以 bool 响应,但它是 Json,所以它在浏览器中的类型是 String 而不是 bool.

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.

因此,如果我在想要检查 "false" == false 时运行 (!data) 则它们不起作用.

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

那么如何在 JavaScript 中从 String 解析 bool 呢?

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

"true" == true"false" == false.然后代码 (!data) 可以检查它是什么 [truefalse]

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

推荐答案

我会明确检查字符串 "true".

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

let data = value === "true";

否则你可以使用 JSON.parse() 将其转换为原生 JavaScript 值,但如果您知道它只是字符串 "true""false,则会产生很多开销" 你会收到的.

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.

相关文章