JS类型的布尔转换

发布于 2025-02-06 13:42:59 字数 262 浏览 1 评论 0 原文

所有3种方法是否都使用相同的转换来进行布尔?

function check(variable){
    let b1 = Boolean(variable);
    let b2 = !!variable;
    let b3 = variable ? true : false;
    
    return b1 === b2 && b2 === b3;
}

Do all 3 ways use the same conversion to bool?

function check(variable){
    let b1 = Boolean(variable);
    let b2 = !!variable;
    let b3 = variable ? true : false;
    
    return b1 === b2 && b2 === b3;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜访吸血鬼 2025-02-13 13:42:59

所有3种方法是否使用相同的转换来bool?

是的。 a href =“ https://tc39.es/ecma262/#sec-logical-not-operator” rel =“ nofollow noreferrer”>逻辑不是操作员条件操作员所有人都通过内部 toboolean algorithm

“在此处输入映像说明”

(当然,Engines可以自由实现它,但是他们想要,但必须按照规范规定的行为)

Do all 3 ways use the same conversion to bool?

Yes. The Boolean function, the logical NOT operator and the conditional operator all convert the value to a boolean value via the internal ToBoolean algorithm:

enter image description here

(of course engines are free to implement it however they want, but it has to behave like the spec dictates)

懒猫 2025-02-13 13:42:59

不要使用布尔对象将非树状值转换为
布尔值。为了执行此任务,请使用布尔值
功能,或双重操作员:

const x = Boolean(expression);     // use this...
const x = !!(expression);          // ...or this
const x = new Boolean(expression); // don't use this!

根据文档,第一种形式等同于第二形式并查看第二种形式,您可以推断出它等同于您建议的第三种形式。

因此,您的所有三种方式都应等效,并且它们取决于 真实

关于为什么您不应该使用 new Boolean()将某些内容转换为布尔值,

MDN Web Docs tell us the following:

Do not use a Boolean object to convert a non-boolean value to a
boolean value. To perform this task, instead, use Boolean as a
function, or a double NOT operator:

const x = Boolean(expression);     // use this...
const x = !!(expression);          // ...or this
const x = new Boolean(expression); // don't use this!

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 value

As 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文