繁体   English   中英

Array.prototype.includes在Node js版本<= 4上

[英]Array.prototype.includes on Node js versions <= 4

我编写了一个Gruntfile,它大量使用了Array.prototype.includes()和类似的函数。 我发现我需要将节点版本降级到4.4.5版本。 一旦我这样做,我就不能长时间使用if ( myarray.includes(somevalue) )语句,并且它会失败说: >> TypeError: myarray.includes is not a function. 当我查看节点文档时,它似乎是当前版本的节点,所以我不确定是什么替代方案。

在节点4及以下的版本中,数组'includes'的等价物是什么? 另外,还有其他我需要注意的巨大差异吗? (另一个我发现在函数声明中不支持默认参数)。

您可以随时只使用polyfill includes以便继续使用它。 甚至还有一个“官方”填充工具在这里

无论如何,除此之外,等价的是indexOf方法,如果找不到该项,则返回-1否则返回其索引。 所以

array.includes(item);

可以替换为

array.indexOf(item) !== -1;

处理这种情况的最佳方法是放入一个polyfill,以允许您运行代码而无需修改它,因为修改可能会导致错误。 您正在寻找的polyfill可以在这里找到 要使用它,您需要在尝试使用.includes之前运行此代码,通常在应用程序启动的任何位置。

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, 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;

      // 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);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        // c. Increase k by 1. 
        k++;
      }

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

暂无
暂无

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

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