【问题标题】:undefined, how you work?未定义,你是怎么工作的?
【发布时间】:2013-02-07 10:58:50
【问题描述】:

只是一个简单的问题:)

如果我有:

var user = {'name': 'Fred'};

所以

console.log(user.name); // Fred
console.log(user.age); // undefined

但是

console.log(test); // ReferenceError: test is not defined

我不明白为什么,因为对我来说它和

一样
console.log(window.test); // undefined

在我的项目中,我尝试检查是否存在全局变量,但我有一个referenceError...我真的不明白为什么followinf代码不起作用...

if (TestGlobal) // ReferenceError: TestGlobal is not defined
   console.log(' allo 1 ');

if (typeof(TestGlobal ) !== 'undefined') // Ok
   console.log(' allo 1 ');

【问题讨论】:

  • 请注意,将变量 test 引用为 window 的属性test 是全局变量时才起作用。
  • 对不起,双重问题,感谢您的回答:)

标签: javascript undefined referenceerror


【解决方案1】:

...和一个简单的答案:

  • 只要基值不是未定义的,属性引用总是计算其值或 undefined 值(如果键不存在)(然后会引发 TypeError)。
  • 如果之前未定义变量,则抛出 ReferenceErrors,除非它们与 typeof keyword 一起使用(它们只计算为 "undefined")。

【讨论】:

    猜你喜欢
    • 2012-11-01
    • 2010-09-06
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    相关资源
    最近更新 更多