在没风的地方找太阳  在你冷的地方做暖阳 人事纷纷  你总太天真  往后的余生  我只要你 往后余生  风雪是你  平淡是你  清贫也是你 荣华是你  心底温柔是你  目光所致  也是你 想带你去看晴空万里  想大声告诉你我为你着迷 往事匆匆  你总会被感动  往后的余生  我只要你 往后余生  冬雪是你  春花是你  夏雨也是你 秋黄是你  四季冷暖是你  目光所致  也是你 往后余生  风雪是你  平淡是你  清贫也是你 荣华是你  心底温柔是你  目光所致  也是你
jQuery火箭图标返回顶部代码 - 站长素材

如何手动实现filter

思路

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 ]
[]

 

posted @ 2020-03-19 10:43  艺术诗人  阅读(677)  评论(0编辑  收藏  举报