【问题标题】:how to make a function add which works in javascript - console.log(add(2)(3)(4)) //9 [duplicate]如何制作一个在 javascript 中可用的函数 add - console.log(add(2)(3)(4)) //9 [重复]
【发布时间】:2022-11-30 18:16:10
【问题描述】:

添加无限数字的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(Sum(2)(3)(4)()) 即最后一个空括号,有没有办法通过更改函数来做到这一点,以便没有空括号的控制台日志给出正确的结果,目前它抛出一个错误,指出 Sum 不是一个函数

【问题讨论】:

  • 不,这显然是不可能的。您可以返回一个函数或一个数字,但不能同时返回两者。
  • 您可以通过覆盖返回的内部函数的 toString 来实现。检查重复项

标签: javascript recursion currying


【解决方案1】:

您可以实现 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

【讨论】:

    【解决方案2】:

    我认为您正在寻找 js 中的 reducer 函数。这是一个例子:

    const myDigits = [1, 2, 3, 4];
    
    const initialValue = 0;
    
    function sumAllDigits(arrayToReduce) {
      return arrayToReduce.reduce(
        (accumulator, currentValue) => accumulator + currentValue,
        initialValue
      );
    }
    
    const result = sumAllDigits(myDigits);
    console.log(result);

    reduce() 方法对数组的每个元素执行用户提供的“reducer”回调函数,按顺序传入对前一个元素计算的返回值。在数组的所有元素上运行 reducer 的最终结果是一个单一的值。

    您可以阅读更多相关信息并查看一些示例here one MDN

    【讨论】:

    • 您好,感谢您的回答,但不同之处在于调用函数的方式,在我的问题中,它是通过在每次调用后传递数字来调用的,这里是用数组调用的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多