js实现filter

Array.prototype.fakeFilter = function fakeFilter(fn, context) {
  if (typeof fn !== "function") {
    throw new TypeError(`${fn} is not a function`);
  }
  
  let arr = this;
  let temp = [];

  for (let i = 0; i < arr.length; i++) {
    let result = fn.call(context, arr[i], i, arr);
    if (result) temp.push(arr[i]);
  }
  return temp;
};

 

posted @ 2020-04-13 23:06  想学JS的前端  阅读(535)  评论(0编辑  收藏  举报