【问题标题】:What does 'typeof' operator tells here?'typeof' 运算符在这里说明了什么?
【发布时间】:2013-05-24 09:19:48
【问题描述】:

代码是:

 var someVariable;    // this variable is declared but not initialised...

 alert(typeof someVariable);   // alerts 'undefined'
 alert(typeof notDeclared);    // also alerts 'undefined' irrespective 
                               //  of the fact it has not been declared..

这似乎有点混乱。现在,如果我这样做了

alert(someVariable);    // again alerts 'undefined'
alert(notDeclared);     // causes an error

jsFiddle 链接:http://jsfiddle.net/gjYZt/2/

如果'typeof notDeclared'未定义,那么当我警告'notDeclared'时,它也应该警告'undefined'而不是给出错误。

【问题讨论】:

    标签: javascript typeof


    【解决方案1】:

    简答:

    typeof 具有不可解析引用的特殊情况;如果引用不可解析,它会显式返回 undefined

    长答案:

    typeof 运算符对不可解析的引用有一个特殊情况:

    11.4.3 typeof 运算符

    产生式 UnaryExpression : typeof UnaryExpression 评估如下:

    1. val 为计算 UnaryExpression 的结果。
    2. 如果 Type(val) 是 Reference,那么
      1. 如果 IsUnresolvableReference(val) 为 true,则返回“undefined”。
      2. val 为 GetValue(val)。
    3. 根据表 20 返回由 Type(val) 确定的字符串。

    另一方面,在 javascript 中随处使用的内部 GetValue(V) 函数,包括用于检索变量的值,如果引用不可解析,则会引发 ReferenceError:

    8.7.1 获取值(V)

    1. 如果 Type(V) 不是引用,则返回 V
    2. 让 base 成为调用 GetBase(V) 的结果。
    3. 如果 IsUnresolvableReference(V),则抛出 ReferenceError 异常。
    4. 如果 IsPropertyReference(V),那么
      [...]

    the spec

    【讨论】:

      【解决方案2】:

      someVariable 声明为 not initialized。但 notDeclared 未声明..

      someVariable 不包含任何默认值。但notDeclared 不可用。

      【讨论】:

      • 这并不能解释为什么typeof 不会为notDeclared 发出错误信号。但我没有投反对票。
      • 好的,谢谢你的信息。如果你投了反对票,最好给出解释
      【解决方案3】:

      当我执行 'alert(typeof notDeclared);' 时,也应该给出一个 错误。不是吗?

      不,因为the specification is clear表示如果typeof的操作数不可解析,typeof的结果一定是undefined(看2a)。

      当您尝试评估无法解析的表达式时,例如您的示例中的 notDeclared,您会收到 ReferenceError - 这也是根据规范。

      【讨论】:

        【解决方案4】:

        运算符 typeof 返回操作数的类型。

        这个列表总结了 typeof 可能的返回值

        Type    Result  
        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"  
        E4X XML object  "xml"  
        E4X XMLList object  "xml"    
        Any other object    "object"  
        

        如果您的警报返回未定义,那是因为您的变量类型未定义。

        问候

        【讨论】:

        • 如果给定一个不存在的变量,这在哪里说它不会发出错误信号?
        • @RobG 当然,但这不在他的回答中。
        猜你喜欢
        • 1970-01-01
        • 2012-11-12
        • 1970-01-01
        • 1970-01-01
        • 2010-12-30
        • 1970-01-01
        • 2010-12-02
        • 1970-01-01
        相关资源
        最近更新 更多