简体   繁体   English

为什么这个 if 语句以非布尔值成功?

[英]Why does this if statement succeed with a non-boolean value?

var m = 5;
if (m) {
    document.write(m);
}

In my view, m is not a bool type, therefore, this if statement will not be executed.在我看来,m 不是 bool 类型,因此,不会执行此 if 语句。 However, I do see the value of m printed on my screen.但是,我确实在屏幕上看到了 m 的值。 Why?为什么?

You should read about truthy values ( MDN ).你应该阅读真值( MDN )。

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context.在 JavaScript 中,真值是在布尔上下文中遇到时被认为是true值。 All values are truthy unless they are defined as falsy (ie, except for false , 0 , 0n , "" , null , undefined , and NaN ).所有值都是真值,除非它们被定义为假(即,除了false00n""nullundefinedNaN )。

Any number other than 0 is truthy, so if(5) is the same as if(true) . 0 以外的任何数字都是真值,因此if(5)if(true)相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM