js怎么判断数组中是否包含NaN

965 阅读1分钟

看到这个问题,首先想到了es6中数组的includes方法,includes方法能够判断数组中是否包含NaN

// 返回true
[1, 2, NaN].includes(NaN);

于是打开MDN搜索数组的includes方法,地址是developer.mozilla.org/zh-CN/docs/… ,滑到下面查看polofill, 如下

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
// 判断数组的原型上是否有includes方法,如果没有则添加上去
if (!Array.prototype.includes) {
  // 在数组原型上添加includes方法
  Object.defineProperty(Array.prototype, 'includes', {
    // 这就是我们要找的内容
    // 参数有两个,valueToFind要在数组中查找的内容,fromIndex从数组的哪个下标开始查找
    value: function(valueToFind, fromIndex) {
      // 所调用的数组为空,则报错
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);
      
      // 使用无符号左位移将长度变为数字
      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;
      
      // 长度为0则直接返回false
      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 如果方法第二个参数为负数,则从后往前数几个做为开始下标
      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      // 判断是否相等,可以看出使用严格相等运算符,
      // 第二个条件就是判断数组中是否存在NaN
      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 从下标为fromIndex开始循环数组查找与valueToFind相同的元素
      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(valueToFind, elementK) is true, return true.
        if (sameValueZero(o[k], valueToFind)) {
          return true;
        }
        // c. Increase k by 1.
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

可以看出判断数组中是否存在NaN的条件是, 两个值是number类型, 并且两个值都是NaN,