javascript问题添加无穷大的数字,后面没有空括号
我试过这个:
const Sum = function (a) {
function innerFunc (b) {
console.log("B", b)
return b ? Sum(a + b) : a;
}
}
console.log(Sum(2)(3)(4))但它适用于console.log(和(2)(3)(4)())(最后为空括号)(最后是空括号),是否有办法更改函数,使没有空括号的控制台日志得到正确的结果,目前它抛出一个错误,说明Sum不是函数
发布于 2022-11-30 10:10:40
您可以实现toString并在需要字符串的函数中使用它。
function add(...args) {
let total = 0;
function sum (...args) {
total += args.reduce((a, b) => a + b, 0);
return sum;
}
sum.toString = function () {
return total;
}
return sum(...args);
}
console.log(add(1, 2, 3)); // 6
console.log(add(1)(2)(3)); // 6
console.log(add(1, 2)(2)(3)); // 8
console.log(add(1, 6)(2, 2)(3)); // 14
console.log(add(1, 6)(2, 2)(3, 4, 5, 7)); // 30
更高级的版本也可以在Symbol.toPrimitive中使用该函数进行计算。
function add(...args) {
let total = 0;
function sum (...args) {
total += args.reduce((a, b) => a + b, 0);
return sum;
}
sum[Symbol.toPrimitive] = function (hint) {
return (['string', 'default'].includes(hint))
? total
: sum;
};
return sum(...args);
}
console.log(add(1, 2, 3)); // 6
console.log(add(1)(2)(3)); // 6
console.log(add(1, 2)(2)(3)); // 8
console.log(add(1, 6)(2, 2)(3)); // 14
console.log(add(1, 6)(2, 2)(3, 4, 5, 7)); // 30
console.log(add(1, 2)(3, 4) + 32); // 42
https://stackoverflow.com/questions/74625818
复制相似问题