【问题标题】:When comparing with null, why == is used in underscore.js and not ===?与null比较时,为什么underscore.js中使用==而不是===?
【发布时间】:2015-01-11 12:46:59
【问题描述】:

没有问题,我只是想知道,在浏览源代码时。 在这里,Why === faster than == in JavaScript? 它说=== 实际上更快,那么为什么在这种情况下使用==

_.each = _.forEach = function(obj, iteratee, context) {
    if (obj == null) return obj;

【问题讨论】:

  • 你能提供更多的上下文吗?有什么问题吗?
  • == 用于相同的值,=== 用于相同的值和对象类型。
  • @Leonel: s/object type/data type/
  • @FelixKling 是的,没错。

标签: javascript underscore.js


【解决方案1】:

你会得到答案here

“==”运算符在进行必要的转换后比较是否相等,因为“===”不会进行任何转换。因此,“===”操作符比“==”操作符快。 但是在您的代码中,如果 obj 为 null 或未定义,则会进行验证。 例如。

var obj=null

obj==undefined //true
obj==null      //true

obj===undefined //false   **This is the difference
obj===null      //true

【讨论】:

    【解决方案2】:

    很可能是因为x == nulltrue(仅用于)x = null x = undefined。 IE。您可以通过一次比较来捕获这两种情况。

    这是松散比较有用的少数例外情况之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 2015-08-05
      • 2014-08-25
      • 2020-09-15
      相关资源
      最近更新 更多