gpt4 book ai didi

javascript - (我失败了)Javascript 挑战 : function add()()() with closures

转载 作者:行者123 更新时间:2023-11-30 08:35:03 25 4
gpt4 key购买 nike

需要编写一个函数,最多可以获取 3 个参数并返回一个总和。这是一种方法,如何调用它:

add(2, 5, 10); // 17
add(2, 5)(10); // 17
add(2)(5)(10); // 17
add(2)(5, 10); // 17

我写了一个函数,可以做到:

function add(a) {
var currentSum = [].reduce.call(arguments, function(c, d) { return c + d; });

function f(b) {
currentSum += [].reduce.call(arguments, function(c, d) { return c + d; });
return f;
}

f.toString = function() {
return currentSum;
};

return f;
}

但是!挑战任务说我不能使用 valueOf 的 toString 来获得结果。我该如何解决?

附言我注意到我没有通过挑战,所以我为什么要问。

最佳答案

我认为你需要做的是,一旦你处理了 3 个参数,你将必须返回总和,而不是函数

function add() {
var sum = 0,
counter = 0;

function local() {
[].some.call(arguments, function(value) {
sum += value;
return ++counter >= 3;
})

return counter < 3 ? local : sum;
}

return local.apply(this, arguments)
}

snippet.log(add(10, 5, 2));
snippet.log(add(10)(5, 2));
snippet.log(add(10)(5)(2));
snippet.log(add(10, 5)(2));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

关于javascript - (我失败了)Javascript 挑战 : function add()()() with closures,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32264835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com