【问题标题】:why using NULL with logical operator throws error in JS为什么在 JS 中使用 NULL 和逻辑运算符会引发错误
【发布时间】:2013-03-11 23:16:26
【问题描述】:

这是我正在测试的代码 --

工作正常

document.write( 1 && undefined ); // prints undefined
document.write( 1 && 3 ); // prints 3 
document.write( 1 && true ); // prints  true

抛出错误

document.write( 1 && NULL ); // throws Error 

为什么使用 NULL 会引发错误,即使它对 undefined 也有效

虽然我测试了 typeof NULL 并给出了 undefined 但它仍然无法正常工作。让我知道这一点。 (OOP 编程新手)

【问题讨论】:

  • @Trailcoder 你可以试试 document.write(1 && null);
  • 添加它以使其工作:var NULL = null;

标签: javascript null logical-operators


【解决方案1】:

NULL 未定义,因为它不存在。你在想null

【讨论】:

    【解决方案2】:

    document.write(1 && null); 输出null

    NULL 在 JavaScript 中不存在,因为它区分大小写。必须是null

    【讨论】:

      【解决方案3】:

      它是null(小写),而不是NULL(大写)

      【讨论】:

        【解决方案4】:

        因为undefined 与不存在的符号不同,所以浏览器会抛出错误。从 Chrome 控制台:

        > 1 && null
        null
        > 1 && NULL
        ReferenceError: NULL is not defined
        > NULL
        ReferenceError: NULL is not defined
        

        【讨论】:

          【解决方案5】:

          NULL不存在,试试这个

          try {
              document.write( 1 &&  NULL  );
          } catch ( e) {
              document.write( 1 &&  null  );
          }
          

          【讨论】:

            【解决方案6】:

            阅读这篇文章可能会回答你的问题 JavaScript undefined vs. null

            【讨论】:

              【解决方案7】:

              使用typeof something 只会给出该表达式的类型;在这种情况下是undefined,因此使用该符号自然会产生错误。同理:

              typeof unknownvar
              // "undefined"
              unknownvar
              // ReferenceError: unknownvar is not defined
              

              符号undefined 本身例外:

              typeof undefined
              // "undefined"
              undefined
              // undefined
              

              在您的特定情况下,NULL 应该是 null

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2015-07-03
                • 2010-10-29
                • 1970-01-01
                • 2014-07-01
                • 1970-01-01
                相关资源
                最近更新 更多