简体   繁体   English

如果(obj!== obj)有事吗?

[英]if (obj !== obj) does somethig?

In this page you can see the following example of how to implement an indexOf for arrays: 此页面中,您可以看到以下示例,该示例如何为数组实现indexOf:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n)    // <-- code of interest
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}

My question is about the line: 我的问题是关于这条线的:

if (n !== n)

in which case would this boolean expression return true ? 在这种情况下,此布尔表达式将返回true吗?

it's a shortcut for verifying if the number is NaN. 这是验证数字是否为NaN的快捷方式。
say if you have n = Number("string"); 告诉您是否有n = Number("string"); then n !== n would evaluate to true . 那么n !== n将评估为true
in this case you could've use if(isNaN(n)) instead of if(n !== n) . 在这种情况下,您可以使用if(isNaN(n))代替if(n !== n)

That is how you check for NaN . 那就是您检查NaN They are probably doing this as a precaution because it is possible to over write the global function isNaN . 他们可能这样做是为了预防,因为可能会覆盖全局函数isNaN

// most of the time you don't need to try to simulate the specification so exactly- //在大多数情况下,您无需尝试模拟规格,因此完全可以-

if(!Array.prototype.indexOf){ 
    Array.prototype.indexOf= function(what, i){
        if(i==undefined || isNaN(i)) i= 0;
        var L= this.length;
        while(i< L){
            if(this[i]=== what) return i;
            ++i;
        }
        return -1;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM