【问题标题】:Javascript != not converting for null?Javascript!=不转换为null?
【发布时间】:2011-10-07 01:46:49
【问题描述】:

我有以下成语:

if(typeof prop != 'null') {
}

我的印象是,如果propnull!=操作符会将空对象转换为字符串'null'进行比较?

在上述情况下,当 prop 为 null 时,表达式被评估为 true。为什么这个成语适用于未定义? undefined 不是一个对象吗?就像 null 是一个对象一样?

【问题讨论】:

  • 您是在比较字符串“null”,而不是 null 对象,所以 (null != 'null')true
  • @Cory Larson - 当然,我认为它可能更像if("1" == 1) // true
  • 数字和空字符串比其他任何东西都更容易获得这种行为。您应该研究 JavaScript 中的“真”和“假”比较。

标签: javascript comparison operators


【解决方案1】:

空对象的类型仍然是“对象”。如果你 alert(typeof prop) 你会看到它是一个对象。

你想检查一个空值。

if(prop == null) {
    alert(typeof prop);
}

【讨论】:

  • Jason Dean - 你确实是对的 - 是 typeof 的使用让我感到困惑。
  • 运行typeof(null)返回object,而typeof(undefined)返回undefined
  • 对我来说很有意义。未定义的引用不能有类型,它是未定义的。但是具有空值的对象仍然是一个对象。
  • @wulfgar.pro undefined 的类型是未定义的字符串。 typeof(undefined) != undefined // true typeof(undefined) === "undefined" // true
  • 对,typeof 返回一个字符串,告诉你类型是什么。 typeof(object) 是字符串“object”,typeof(undefined) 是字符串“undefined”。 typeof 总是返回一个字符串。
【解决方案2】:

使用 firebug 或 dom insperctor 看看 typeof prop 是什么

console.log(typeof prop);

也许你也可以试试这个

if(prop != null) {

}

if(typeof prop != undefined) {
}

取决于你真正想要做什么/

【讨论】:

    【解决方案3】:

    我相信您只需要从 'null' 中删除引号

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-25
      • 2017-01-10
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      相关资源
      最近更新 更多