filter 方法接收两个参数:

  • 对每一项执行的函数
    • 该函数接收三个参数:
      • 数组项的值
        数组项的下标
        数组对象本身
  • 指定 this 的作用域对象

filter 方法返回 执行结果为true的项组成的数组。

代码表示:

arr.filter(function(item, index, arr){}, context)

实现

由此,实现 fakeFilter 方法如下

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;
};

检测

let arr = ["x", "y", "z", 1, 2, 3];

console.log(arr.filter((item, index, arr) => console.log(item, index, arr)));

输出

x 0 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
y 1 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
z 2 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
1 3 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
2 4 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
3 5 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
[]

 

相关文章:

  • 2022-02-20
  • 2021-09-26
  • 2021-05-09
  • 2021-09-06
  • 2021-08-27
  • 2021-04-06
  • 2021-05-28
  • 2021-07-19
猜你喜欢
  • 2022-12-23
  • 2019-12-15
  • 2021-10-25
  • 2021-05-16
  • 2021-12-10
  • 2022-12-23
  • 2021-06-30
相关资源
相似解决方案