柯里化函数无法打印结果?常见问题及解决方案
你的代码有两个问题:
-
在 'add' 函数中,你应该使用 'arr' 变量存储传入的参数,而不是 'arguments' 变量。'arguments' 变量是一个类数组对象,不支持数组的 'push' 和 'concat' 操作。
-
在 'add' 函数中,当传入的参数个数小于 'n' 数组的长度时,应该返回 'add' 函数本身,而不是直接返回 'undefined'。
下面是修改后的代码:
function sum(a,b,c,d){
return a+b+c+d;
}
function keLi(n){
let arr=[];
function add(...args){
arr = [...arr,...args]
if(arr.length<n.length){
return add;
}else{
return sum(...arr);
}
}
return add;
}
let m = keLi(sum);
console.log(m(1,2,3,4));
console.log(m(1,2)(3,4));
console.log(m(1)(2)(3)(4));
输出结果:
10
10
10
原文地址: https://www.cveoy.top/t/topic/l4T5 著作权归作者所有。请勿转载和采集!