【问题标题】:Why typeof undefined is return string? [duplicate]为什么 typeof undefined 是返回字符串? [复制]
【发布时间】:2014-06-17 07:33:50
【问题描述】:

当我从浏览器运行时

typeof undefined

我得到了"undefined" 字符串。因此?大多数时候我会检查我的变量,比如

if (a == 'undefined') {
  do something
}

我是否正在检查我的变量 a 是否等于未定义?我不明白这一点。有人可以解释一下吗?在 javascript 中检查 undefined 的另一种方法?

【问题讨论】:

  • 这样做 -> if(typeof a === 'undefined'){<...>}
  • typeof 返回值的数据类型的名称(或多或少)。并且名称表示为字符串。
  • 还有什么方法可以检查未定义的?
  • 您还可以将该值与undefined 进行比较。例如。 v === undefinedv === void 0v == null(捕获未定义和空值)。

标签: javascript undefined


【解决方案1】:

因为typeof 就是这样工作的:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

if (a == undefined) { // instead its a type comparison 

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      undefined 恰好是一个包含the undefined value 的全局名称。

      引用链接页面,

      undefined 是全局对象的属性,即它是全局范围内的变量。
      undefined 的初始值是原始值 undefined。

      typeof 总是返回一个字符串,描述传递给它的名称的值。

      【讨论】:

        【解决方案4】:

        typeof 运算符返回一个字符串,指示未计算的操作数的类型。

        变化是这样的

        Undefined   :"undefined"
        Null    :"object"
        Boolean :"boolean"
        Number  "number"
        String  :"string"
        Host object (provided by the JS environment)    :Implementation-dependent
        Function object (implements [[Call]] in ECMA-262 terms):    "function"
        Any other object    :"object"
        

        DOC

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-10
          • 1970-01-01
          • 2013-08-19
          • 2014-05-11
          • 1970-01-01
          • 2011-02-17
          相关资源
          最近更新 更多