JavaScript 实现 filter() 方法函数

xiaoxiao2021-02-28  10

思路

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.fakeFilter(item => typeof item === "string"));

输出

[ ‘x’, ‘y’, ‘z’ ]

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

相关

迭代: JavaScript 实现 map() 方法函数

归并: JavaScript 实现 reduce() 方法函数

转载请注明原文地址: https://www.6miu.com/read-2650078.html

最新回复(0)