簡體   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