【问题标题】:Is there any function difference between using != null and != undefined in javascript?在 javascript 中使用 != null 和 != undefined 之间有什么功能区别吗?
【发布时间】:2019-07-07 12:55:54
【问题描述】:

在javascript中,使用!= null!= undefined有什么功能区别?

您是否可以为myVar 分配一个值,这会导致这两行代码得出不同的结果?

console.log(myVar != undefined)
console.log(myVar != null)

如果您对这两个操作的性能有所了解,我也很想知道。

【问题讨论】:

  • 性能应该是您最不关心的问题。 myVar 的可能值是多少?
  • @r3zaxd1 有用的链接,谢谢。但我的问题不同。这是关于不等式运算符,而不是 null 和 undefined 比较的性质。
  • @Teemu 我打错了,我现在会编辑并修复它。

标签: javascript null operators undefined null-check


【解决方案1】:

没有功能上的区别。当xnullundefined 时,x != undefinedx != null 都只计算为false。对于 x 的所有其他值,它们都评估为 true。

也没有性能差异。

【讨论】:

    【解决方案2】:

    没有区别,您可以在下表中看到 JS == 测试(关注空/未定义的行/列)(src:here)。所以myVar!=null 只有当myVar 值不是null 而不是undefined 时才为真(与myVar != undefined 相同)

    看起来两者的性能相似(我在 Mac OS X 10.13.4 HighSierra 上进行了测试:Chrome 71.0.3578、Firefox 65.0.0 和 Safari 11.1.0 - 您可以在浏览器中运行测试 here

    let myVar1=null;
    let myVar2=undefined;
    

    【讨论】:

      【解决方案3】:

      ==!= 运算符进行“类型转换”以仅比较值本身。那么不,在这种情况下使用“未定义”或“空”没有区别,都表示“空”。

      但是,如果您使用 ===!== 代替,它会检查类型和值,而不进行任何类型转换。两条线的结果会有所不同。

      myVar = null;
      console.log(myVar !== undefined) //true
      console.log(myVar !== null) //false
      

      【讨论】:

        【解决方案4】:

        不要混淆undefinednull,因为它们不是同一个东西。

        空:

        值 null 表示有意不存在任何对象值。它是 JavaScript 的原始值之一。

        未定义:

        未赋值的变量是未定义类型。如果正在评估的变量没有赋值,则方法或语句也会返回 undefined。如果没有返回值,则函数返回 undefined。


        如果变量包含既不是null 也不是undefined 的值,那么你的情况没有区别。

        const value = 3;
        
        console.log(value !== undefined) //true
        console.log(value !== null) //true

        但是,测试变量是否为nullundefined 的更好方法是使用! 否定作为值nullundefined 将被解析为true。

        const undefinedValue = undefined;
        const nullValue = null;
        
        console.log(!undefinedValue);
        console.log(!nullValue);

        这里有一些例子。

        var someVariable = undefined;
        
        console.log(someVariable !== undefined, "; undefined !== undefined");
        console.log(someVariable !== null, "; undefined !== null");
        
        var someVariable = null;
        
        console.log(someVariable !== undefined, "; null !== undefined");
        console.log(someVariable !== null, "; null !== null");
        
        
        var someVariable = undefined;
        console.log(!someVariable);
        
        var someVariable = null;
        console.log(!someVariable);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-29
          • 1970-01-01
          • 2018-10-23
          • 2018-03-19
          • 2011-12-03
          • 1970-01-01
          • 2017-11-16
          • 2023-03-18
          相关资源
          最近更新 更多