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

重写invoke函数时无法传递参数,求助解决方法

解决_.invoke函数的参数传递问题

你的代码已经正确收集了要传递的参数,但核心问题是调用目标方法时没有把收集到的参数传进去,同时数组和对象的遍历逻辑可以合并简化。

修改后的代码

_.invoke = function (collection, methodName) {
  const newArr = [];
  const args = Array.prototype.slice.call(arguments, 2);
  // 统一获取集合中的所有元素,兼容数组和对象
  const elements = Array.isArray(collection) ? collection : Object.values(collection);
  
  elements.forEach(element => {
    // 兼容methodName是函数或字符串的情况(符合Lodash invoke的特性)
    const targetMethod = typeof methodName === 'function' ? methodName : element[methodName];
    // 用apply传递参数数组,同时绑定this为当前元素
    newArr.push(targetMethod.apply(element, args));
  });

  return newArr;
};

关键修改说明

  1. 参数传递修复:用targetMethod.apply(element, args)替代原代码的element[methodName](),apply会把args数组中的元素逐个传递给目标方法,同时将方法的this上下文绑定为当前遍历的element。如果习惯ES6语法,也可以用call配合展开运算符:targetMethod.call(element, ...args)。
  2. 遍历逻辑简化:不再分开判断数组和对象,用Object.values直接获取对象的所有值,数组则直接使用自身,减少重复代码。
  3. 兼容函数类型的methodName:Lodash的invoke支持传入方法名(字符串)或直接传入函数,这里增加了对函数类型的处理,让实现更贴近原生Lodash的行为。

内容的提问来源于stack exchange,提问作者vadim-nest

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 05:24:17