【问题标题】:Set a variable undefined and null设置一个变量 undefined 和 null
【发布时间】:2014-11-17 06:32:52
【问题描述】:

我刚刚阅读了一些代码,我看到了这一行:

var foo = null, undefined;

当我测试变量时,它既是空的又是未定义的。

所以我的问题是,将变量设置为 null 和 undefined 的目的是什么? 我不明白。 谢谢你的解释。

【问题讨论】:

  • foo 变量将是nullundefined 在上面的语句中没有用
  • 因此,这个声明是一个死代码?
  • 检查未定义时要小心,使用 === 或 typeof
  • 你如何检查那个变量它既是空的又是未定义的

标签: jquery variables


【解决方案1】:

如 cmets 中所述,您可能没有以正确的方式测试 foo,变量不能同时为 undefined null。

var foo = null, undefined;
alert(foo); //shows null
alert(typeof foo); //shows object (not undefined)

那么发生了什么?逗号表示您正在声明一个附加变量。由于 undefined 已经是关键字,因此语句的这个特定部分无效。但是,如果你这样做:

var foo = null, undefined1;
alert(foo); //shows null
alert(typeof foo); //shows object (not undefined)
alert(undefined1); //shows undefined
alert(typeof undefined1); //shows undefined

您可以看到您实际上是在声明一个新变量undefined1,它没有初始值。

【讨论】:

    【解决方案2】:

    该语句的目的是在同名变量中声明 undefined

    例如:

    // declare two local variables
    var foo = null, undefined;
    
    console.log(foo === undefined); // false
    

    类似于:

    function test(foo, undefined)
    {
        console.log(foo === undefined); // false
    }
    test(null); // only called with a single argument
    

    这通常不是必需的,因为理智的浏览器不允许任何人重新定义 undefined 的含义,jslint 会抱怨这个:

    保留名称“未定义”。

    基本上,我建议不要这样做:

    var foo = null;
    

    顺便说一句,不要将上述声明与以这种方式使用comma operator 混淆:

    var foo;
    
    foo = 1, 2;
    console.log(foo); // 2
    

    【讨论】:

      【解决方案3】:

      短:没用的

      没有分配任何变量是undefined。您可以分配null 使其为空。但是你的比较也很重要

      Fiddle Demo

      if(foo == null) //true
          alert('1');
      if(foo == undefined) //true
          alert('2');
      

      现在严格比较 ===

      if(foo === null) //false............can be true if assigned to null
          alert('3');
      if(foo === undefined) //true.......can be flase if assigned to null
          alert('4');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-15
        • 2013-02-13
        • 1970-01-01
        • 2013-07-18
        • 1970-01-01
        • 2019-05-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多