JS类型的布尔转换
所有3种方法是否都使用相同的转换来进行布尔?
function check(variable){
let b1 = Boolean(variable);
let b2 = !!variable;
let b3 = variable ? true : false;
return b1 === b2 && b2 === b3;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。 a href =“ https://tc39.es/ecma262/#sec-logical-not-operator” rel =“ nofollow noreferrer”>逻辑不是操作员和条件操作员所有人都通过内部
toboolean
algorithm :(当然,Engines可以自由实现它,但是他们想要,但必须按照规范规定的行为)
Yes. The
Boolean
function, the logical NOT operator and the conditional operator all convert the value to a boolean value via the internalToBoolean
algorithm:(of course engines are free to implement it however they want, but it has to behave like the spec dictates)
根据文档,第一种形式等同于第二形式并查看第二种形式,您可以推断出它等同于您建议的第三种形式。
因此,您的所有三种方式都应等效,并且它们取决于
真实
值关于为什么您不应该使用
new Boolean()
将某些内容转换为布尔值,MDN Web Docs tell us the following:
According to the docs, the first form is equivalent to the second form and looking at the second form, you could deduce that it is equivalent to the third form you suggested.
So all three of your ways should be equivalent and they are dependent on what JavaScript considers as a
truthy
valueAs to why you shouldn't use
new Boolean()
to convert something to boolean, this section offers a bit of an explanation. TL;DR You might accidentally initialize non-truthy values as truthy.