我一直在学习扩展参数,我发现当使用: cur.func.call(null, ...cur.arg, acc), args)
时,如果你有一个空数组,没有参数传递给 add()
。
是否可以在不使用这行代码中看到的 ...
的情况下重现此内容 cur.func.call(null, ...cur.arg, acc), args )
class Lazy {
constructor() {
this.builtUpFuncs = [];
}
add(...newArgs) {
console.info(newArgs)
this.builtUpFuncs.push({
func: newArgs[0],
arg: typeof newArgs[1] === "undefined" ? [] : [newArgs[1]],
});
return this;
}
evaluate(target) {
return target.map((args) =>
this.builtUpFuncs.reduce((acc, cur) =>
cur.func.call(null, ...cur.arg, acc), args)
);
}
}
const lazyClass = new Lazy();
const returnValue =
lazyClass
.add(function timesTwo(a) { return a * 2; })
.add(function plus(a, b) { return a + b; }, 1)
.evaluate([1, 2, 3]);
console.info(returnValue);
最佳答案
如果你想避免扩展语法,传统的方法是使用 apply
而不是 call
:
cur.func.apply(null, cur.arg.concat(acc))
请注意,args
部分是 reduce
的第二个参数,而不是此函数调用。
在任何一种语法中,如果 cur.arg
是空数组,则传递的唯一参数是 acc
,这是正常的。
关于javascript - 将参数传递给函数调用时不使用扩展参数 (...) 进行复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48286800/