【问题标题】:what is the difference between type coercion using Boolean constructor function and inside if使用布尔构造函数的类型强制和内部 if 有什么区别
【发布时间】:2016-10-05 08:42:33
【问题描述】:

请参考这里的jsfiddle,https://jsfiddle.net/reuk08ob/ html: <div id="abc"></div> 脚本:

if(null==false){
  document.getElementById("abc").innerHTML="hello, null == true coerced";
}else if(Boolean(null)==false ){
  document.getElementById("abc").innerHTML="hello, boolean constructor coercion worked! previous one did not,strange, both should do the same, shouldn't they?";
}

我错过了什么吗?布尔构造函数不应该与 if 语句中隐式执行的类型强制相同吗?

【问题讨论】:

    标签: javascript type-coercion


    【解决方案1】:

    Boolean 不做类型强制,它做类型conversion,这意味着类型转换是显式的而不是隐式的。

    here 开始,布尔值的工作方式如下:“如果值被省略或为 0、-0、null、false、NaN、未定义或空字符串 (""),则对象的初始值为 false 。”

    此外,“不要将原始布尔值真假与布尔对象的真假值混淆。”。换言之,布尔构造函数返回一个布尔对象,该布尔对象具有由上述规则确定的值。

    【讨论】:

      猜你喜欢
      • 2011-04-16
      • 2011-10-23
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      相关资源
      最近更新 更多