每天一题,filter

358 阅读1分钟

每天一题,坚持思考

题目

实现filter函数,过滤数组元素

filter([1, 3, 5, 3, 2, 1], function (item) {return item > 2}); // [3, 5, 3]

具体实现

// 判断是否为数组类型
function isArray(args) {
  if (Object.prototype.toString.call(args) === '[object Array]') {
    return true;
  }
}

// 数组过滤方法
function filter(array, executor, context) {
  // 通过判断类型
  var length = isArray(array) ? array.length : 0;
  if (!length) return [];

  if (typeof executor !== 'function') return array;

  var index = -1,
      result = [];
  while (++index < length) {
    if (executor.call(context, array[index], index, array)) {
      result[result.length] = array[index];
    }
  }
  return result;
}

实现思路

参数:

  1. array(Array):需要被过滤的数组;
  2. executor(Function): 每次遍历执行的函数(当前数组成员, 当前索引值, 遍历的数组)
  3. context (*):上下文对象,也就是回调函数中的this绑定的值,默认就是undefined; ;

步骤:

  1. 判断当前的array参数是否为数组,并且判断该数组的长度;
  2. 判断executor的类型是否为函数,如果不是则返回当前数组;
  3. 这里使用while遍历,第一次遍历时index的值为0,最后index的值等于数组的长度值;
  4. 通过call方法调用executor函数并且绑定它的this指向,并且把当前数组成员,索引值,和array作为参数传入executor函数。通过判断返回值是否为true,如果是,则添加到新的数组result里面,result[result.length]是添加数组最后一个元素,这里和push的效果是一样的。

如果读者发现有不妥或者可以改善的地方,欢迎在评论区指出。如果觉得写得不错或者对你有所帮助,可以点赞、评论、转发分享,谢谢~