使用布尔类型与字符串类型"true"/"false"的优缺点是什么? [英] What are the pros and cons of using boolean type versus string type "true"/"false"?

查看:85
本文介绍了使用布尔类型与字符串类型"true"/"false"的优缺点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,我已经看到使用字符串类型表示"true"和"false"的代码.为什么不简单地使用布尔类型呢?

In Javascript, I have seen code using string type to represent "true" and "false". Why not simply use boolean type?

在Java语言中使用布尔类型与字符串类型"true"/"false"的优缺点是什么?还是使用字符串类型表示布尔值只是不好的做法?

What are the pros and cons of using boolean type versus string type "true"/"false" in Javascript? Or is it simply bad practice to use string type to represent boolean values?

推荐答案

字符串"true" "false" 被认为是真实的.因此,切勿使用它们代替布尔值.

String "true" and "false" are considered to be truthy. So, never use them instead of boolean values.

console.log(Boolean("true"));
# true
console.log(Boolean("false"));
# true

console.log(true  != "true");
# true
console.log(false != "false");
# true

这篇关于使用布尔类型与字符串类型"true"/"false"的优缺点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆