function partialize(){
}
function calculation(a,b,c){
console.log(a*b/c);
return a*b/c;
}
var a = 10, b= 20, c= 5;
var partialize1 = partialize(calculation, a);
partialize1(b,c)
var partialize2 = partialize(calculation, a, b);
partialize2(c)
var partialize3 = partialize(calculation, a, b, c);
partialize3()
我需要编写partialize
函数,以在所有same
条件下提供three
输出。
我尽力使它工作。但是我使用了传播算子。没有传播算子我们能做到吗?
function partialize(fn,...a) {
console.log(...a);
return function (...b) {
console.log(...b);
fn(...a,...b);
}
}
function calculation(a, b, c) {
console.log(a * b / c);
return a * b / c;
}
var a = 10, b = 20, c = 5;
var partialize1 = partialize(calculation, a);
partialize1(b, c)
var partialize2 = partialize(calculation, a, b);
partialize2(c)
var partialize3 = partialize(calculation, a, b, c);
partialize3()
如果没有传播算子,我们可以做同样的事情吗?
答案 0 :(得分:3)
您可以保存传递的初始arguments
并返回可以用其余参数调用的函数,然后用apply
调用原始函数:
function partialize(fn) {
const initialArguments = Array.from(arguments).slice(1);
return function() {
const finalArguments = Array.from(arguments);
fn.apply(null, initialArguments.concat(finalArguments));
}
}
function calculation(a, b, c) {
console.log(a * b / c);
return a * b / c;
}
var a = 10,
b = 20,
c = 5;
var partialize1 = partialize(calculation, a);
partialize1(b, c)
var partialize2 = partialize(calculation, a, b);
partialize2(c)
var partialize3 = partialize(calculation, a, b, c);
partialize3()
答案 1 :(得分:1)
如果您的代码当前正在按原样运行,但您希望将其更改为不使用传播运算符,则可以改用arguments对象。
参数对象: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
如果有帮助,还请查看此stackoverflow问题以获取一些与arguments对象一起使用的示例代码。 How can I convert the "arguments" object to an array in JavaScript?
答案 2 :(得分:0)
user944513,要模拟 javascript 中方法的重载,可以使用函数中默认提供的 arguments对象。为了更好地解释您,我编写了一段代码。希望这可以帮助您:
function suma(a = 0){
let resultado = 0;
console.log(arguments.length);
for(let i = 0; i < arguments.length; i++)
{
if(typeof(arguments[i] == "number")){
resultado += arguments[i];
}
}
}
suma(1,2,3,4); // 10
suma(1,2)// 3