JS 手写之 Array.prototype.filter

时间:2021-05-25 18:03:20   收藏:0   阅读:0

Array.prototype.filter

filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

语法

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

参数

返回值

一个新的、由通过测试的元素组成的数组,如果没有任何数组元素通过测试,则返回空数组。

Array.prototype.myFilter

Array.prototype.myFilter = function (callbackFn, thisArg) {
  // 处理回调类型异常
  if (Object.prototype.toString.call(callbackFn) != "[object Function]") {
    throw new TypeError(callbackFn + " is not a function");
  }
  var res = [];
  for (var i = 0, len = this.length; i < len; i++) {
    var exit = callbackFn.call(thisArg, this[i], i, this);
    exit && res.push(this[i]);
  }
  return res;
};

测试

const arr = [1, 2, 3, 4];

arr.myFilter((item) => item > 2); // [3, 4]

arr.myFilter("555"); // Uncaught TypeError: 555 is not a function
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!