布尔对象的意义何在?

2022-01-19 00:00:00 boolean javascript

我正在阅读关于 JavaScript 的 Mozilla 手册,我在阅读中来到了这一点,布尔对象.我看不到它们的单一用途.他们的意义何在?为什么不只使用 truefalse?

I am reading through the Mozilla Manual on JavaScript, and I come to this point in my reading, Boolean object. I can't see a single use for them. What's their point? Why wouldn't you use just true and false?

顺便说一句,我根本不懂 Java,而且我不害怕学习新事物,这也是我尝试学习 JavaScript 的原因.我是一名 PHP 程序员,一名后端人员,我想学习如何做一些前端工作,所以我正在阅读 Mozilla JavaScript 指南.

By the way, I don't know Java at all and I'm not afraid of learning new things that consequently why I'm trying to learn JavaScript. I'm a PHP programmer, a back end guy, and I'd like to learn how to do some front end work, so I'm reading the Mozilla JavaScript Guide.

推荐答案

因为这是(有点遗憾)语言的定义方式——我怀疑它最初是为了性能/优化;请注意下面分配给 string 属性的情况.(Java 的工作方式类似,尽管 Scala 和 Python 在很大程度上拒绝这种区别).

Because this is (somewhat sadly) how the language was defined -- I suspect it was originally for performance/optimization; note the case of assignment to a string property below. (Java works similarly, although Scala and Python largely reject this distinction).

请注意,Boolean 并不是唯一的包装器类型".例如,还有 StringNumber.

Note that Boolean isn't the only "wrapper type". There are also String and Number, for instance.

因此,仍然存在许多怪癖(以下可能同样适用于布尔值):

Because of this there remains a number of quirks (the below could just as much apply to Boolean):

typeof("foo") // string
typeof(new String("foo")) // object
"foo" instanceof String // false
new String("foo") instanceof String // true

// result is undefined: a string is a primitive and silently "ate" the assignment
// this also makes it a much cheaper value as it's not a "real" object
x = "f"; x.bar = 42; x.bar

// result is 42: a String is a "real" object with real properties!
// however, this also means that it may have a good bit more overhead
x = new String("f"); x.bar = 42; x.bar

我知道这并没有回答"这个问题,而是在火上扔了一些木头;-)

I know this didn't "answer" the question, but rather chucks some more wood on the fire ;-)

上述唯一真正的陷阱"可能是 new Boolean(false) 是一个真值.

The only real "gotcha" otherwise from the above is that perhaps new Boolean(false) is a truth-y value.

编码愉快.

相关文章