【问题标题】:Very strange behaviour comparing undefined and false比较未定义和错误的非常奇怪的行为
【发布时间】:2012-06-14 12:40:01
【问题描述】:

我在控制台中有这个输出:

console.log((!undefined)==(!false)) // true (fine)
console.log((!!undefined)==(!!false)) // true (still fine)

据我所知,!!x==x,不是吗?

console.log((undefined)==(false)) // false

谁能告诉我为什么返回 false?

!!false==false!!undefined==undefined 不是真的吗?

【问题讨论】:

标签: javascript comparison logic comparison-operators


【解决方案1】:

是的。 !!x 返回 x。 !undefined 强制 undefined 到布尔值false,然后找到!((bool)undefined)=!false,如果我们使用 C++ 转换符号。所以!!undefined 给出!!((bool)undefined)=!!(false)=!true=false,而不是undefined

【讨论】:

  • 任何(官方)参考强调这种行为?
【解决方案2】:

Undefined 不是 boolean 类型,像 false 所以直接比较它们时,它们是不相等的。

有关其他比较陷阱,请参阅 here

typeof(undefined)
"undefined"

typeof(false)
"boolean"

【讨论】:

  • ===== 在比较 falseundefined/null 时没有区别,尤其是在这种情况下,即使在比较之前所有内容都转换为相同的类型,也没有区别。
  • 抱歉,我不是这个意思。我更新了我的答案以使其更清楚。
【解决方案3】:
console.log(!undefined)
// true
console.log(!false)
// true
console.log(!!undefined)
// false
console.log(!!false)
// false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多