Javascript数组polyfils之映射与过滤器

2025-01-09 12:06:26   小编

Javascript数组polyfils之映射与过滤器

在JavaScript的世界里,数组的映射(map)和过滤器(filter)方法是非常实用的工具。然而,在一些较旧的环境中,可能并不原生支持这些方法,这时候就需要使用polyfils来实现相同的功能。

首先来看看数组的映射方法(map)。map方法用于创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。如果没有原生的map方法,我们可以通过以下polyfil来实现:

if (!Array.prototype.map) {
  Array.prototype.map = function(callback, thisArg) {
    var T, A, k;
    if (this == null) {
      throw new TypeError(' this is null or not defined');
    }
    var O = Object(this);
    var len = O.length >>> 0;
    if (typeof callback!== 'function') {
      throw new TypeError(callback +' is not a function');
    }
    if (arguments.length > 1) {
      T = thisArg;
    }
    A = new Array(len);
    k = 0;
    while (k < len) {
      var kValue, mappedValue;
      if (k in O) {
        kValue = O[k];
        mappedValue = callback.call(T, kValue, k, O);
        A[k] = mappedValue;
      }
      k++;
    }
    return A;
  };
}

接下来是过滤器方法(filter)。filter方法用于创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。其polyfil实现如下:

if (!Array.prototype.filter) {
  Array.prototype.filter = function(func, thisArg) {
    if (!((typeof func === 'Function' || typeof func === 'function') && this))
      throw new TypeError();
    var len = this.length >>> 0,
      res = new Array(len),
      t = this, c = 0, i = -1;
    if (thisArg === undefined) {
      while (++i!== len) {
        if (i in this) {
          if (func(t[i], i, t)) {
            res[c++] = t[i];
          }
        }
      }
    } else {
      while (++i!== len) {
        if (i in this) {
          if (func.call(thisArg, t[i], i, t)) {
            res[c++] = t[i];
          }
        }
      }
    }
    res.length = c;
    return res;
  };
}

通过这些polyfils,我们可以在不支持map和filter方法的环境中使用它们,从而更方便地处理数组数据,提高代码的兼容性和可维护性。

TAGS: JavaScript 数组 过滤器 映射

欢迎使用万千站长工具!

Welcome to www.zzTool.com