【发布时间】:2020-06-01 03:59:46
【问题描述】:
我正在学习 javascript 中的 curry 函数。 我想到了一个问题。
// how to implement the add function in the below.
add(1)(2)(3) = 6;
add(1, 2, 3)(4) = 10;
add(1)(2)(3)(4)(5) = 15;
我已经知道实现的代码
function add() {
var _args = Array.prototype.slice.call(arguments);
var _adder = function () {
_args.push(...arguments);
return _adder;
};
_adder.toString = function () {
return _args.reduce(function (a, b) {
return a + b;
});
}
return _adder;
}
console.log(add(1)(2)(3)(4)(5)) // function
console.log(add(1)(2)(3)) // function
console.log(add(1, 2, 3)(4)) // function
console.log(add(1)(2)(3)(4)(5) == 15) // true
console.log(add(1)(2)(3) == 6) // true
console.log(add(1, 2, 3)(4) == 10) // true
console.log(add(1)(2)(3)(4)(5) === 15) // false
console.log(add(1)(2)(3) === 6) // false
console.log(add(1, 2, 3)(4) === 10) // false
我知道实现的代码是如何工作的。 但我对这个问题很好奇。 在我看来,“add(1)(2)(3) = 6;”意味着执行表达式“add(1)(2)(3)”后,它应该返回一个完全等于数字 6 的值.但是从这个问题及其实现代码来看,我可能对这个问题有误解。那么,这个问题的真正含义是什么?面试官经常会问这个问题。
【问题讨论】:
-
在我的 Chrome 浏览器上,前三个案例返回数字 15、6 和 10,而不是“函数”。
-
另外两个变体:
console.log(typeof add(1)(2)(3)(4)(5))返回“function”,console.log(add(1)(2)(3)(4)(5) +0 === 15)返回“true”。 -
哦。这确实很奇怪。我也用铬。它的版本是 83。
-
我只是在我的 safari(13.1 版)和 firefox(76 版)浏览器中测试代码。在 Firefox 中,前三种情况返回函数。在 safari 中,它返回数字 15、6 和 10。但是当我想查看“add(1)(2)(3)(4)(5)”的类型时,safari 只给我“函数”。
标签: javascript function tostring currying