You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现支持所有原生参数的自定义Array.filter方法

Array.prototype.filter() 可选参数解析与完整自定义实现

可选参数作用说明

原生filter标准语法:

array.filter(callbackFunction(currentValue, index, arr), thisValue)

三个可选参数的作用:

  • index:当前遍历元素在原数组中的索引,从0开始计数
  • arr:调用filter方法的原数组引用,回调中拿到的arr和调用方法的原数组完全一致
  • thisValue:回调函数执行时内部this的绑定值,不传时遵循普通函数默认this规则

你写的基础版已经覆盖了核心筛选逻辑,只需要补全参数传递、this绑定两个部分,再加上边界处理,就能完全对齐原生filter的行为。

完整myFilter实现

const s = [23, 65, 98, 5];

Array.prototype.myFilter = function(callback, thisValue) {
  // 入参合法性校验,对齐原生行为
  if (typeof callback !== 'function') {
    throw new TypeError(`${callback} is not a function`);
  }
  const result = [];
  const source = this;
  const len = source.length;

  for (let i = 0; i < len; i++) {
    // 跳过稀疏数组空槽,对齐原生filter行为
    if (i in source) {
      const current = source[i];
      // 绑定this指向,按顺序传入三个回调参数
      const pass = callback.call(thisValue, current, i, source);
      if (pass) {
        result.push(current);
      }
    }
  }
  return result;
};

验证用例

可以通过以下用例确认三个可选参数的逻辑正常生效:

// 基础功能验证(和原有测试逻辑一致)
const oddNums = s.myFilter(item => item % 2 === 1);
console.log(oddNums); // [23, 65, 5]

// index、arr参数验证
const idxTest = s.myFilter((item, idx, arr) => {
  console.log(`遍历到下标${idx},原数组长度${arr.length}`);
  return idx >= 2;
});
console.log(idxTest); // [98, 5]

// thisValue参数验证
const config = { min: 50 };
const thisTest = s.myFilter(function(item) {
  return item > this.min;
}, config);
console.log(thisTest); // [65, 98]

实现逻辑说明:

  1. 入参校验:传入的第一个参数不是函数时直接抛类型错误,和原生filter行为一致
  2. 提前缓存原数组和长度,避免遍历过程中原数组被修改导致的逻辑异常
  3. 用Function.prototype.call执行回调,第一个参数传入thisValue实现上下文绑定,后续按规范顺序传入当前值、索引、原数组三个回调参数
  4. 增加i in source判断,跳过稀疏数组中不存在的空槽,和原生filter处理稀疏数组的逻辑对齐

内容的提问来源于stack exchange,提问作者Sugarpearl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 03:30:50