重写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; };
关键修改说明
- 参数传递修复:用
targetMethod.apply(element, args)替代原代码的element[methodName](),apply会把args数组中的元素逐个传递给目标方法,同时将方法的this上下文绑定为当前遍历的element。如果习惯ES6语法,也可以用call配合展开运算符:targetMethod.call(element, ...args)。 - 遍历逻辑简化:不再分开判断数组和对象,用
Object.values直接获取对象的所有值,数组则直接使用自身,减少重复代码。 - 兼容函数类型的methodName:Lodash的
invoke支持传入方法名(字符串)或直接传入函数,这里增加了对函数类型的处理,让实现更贴近原生Lodash的行为。
内容的提问来源于stack exchange,提问作者vadim-nest
相关产品推荐
相关产品推荐

