代码之家  ›  专栏  ›  技术社区  ›  Roland

chrome处理未定义的问题是否不同?[副本]

  •  0
  • Roland  · 技术社区  · 6 年前

    我的Asp母版页包含以下代码:

    <script>
        if (theForm !== undefined) { // <<== line 746: error
            theForm.onsubmit = ...bla bla... ;
        }
    </script>
    

    Chrome控制台报告错误:

    Uncaught ReferenceError: theForm is not defined   bla.aspx:746
    

    我的问题是:这是一种错误的方法来检测一个名字是否未被定义?还是Chrome对这个的处理方式不同?

    2 回复  |  直到 6 年前
        1
  •  1
  •   dgeare    6 年前

    声明的变量与值为 undefined 一个从未声明过的变量。我猜你的情况是后者。使用typeof运算符。

    if(typeof(theForm) !== 'undefined'){ //typeof returns a string
    
        2
  •  2
  •   lealceldeiro VonC    6 年前

    信息 Uncaught ReferenceError: theForm is not defined

    theForm is not declared

    为什么? 基本上,变量可以是 undefined

    例子

    1. 声明和 未定义

    var foo;        // if a value would be assigned (i.e.: var foo = 3), then it wouldn't be undefined
    console.log(foo);

    console.log(foo); // <-- foo was never declared

    如何 修理

    使用 typeof 这样地:

      console.log('Is undefined:', typeof foo === 'undefined');