这与此问题有关: Is it possible to spread the input array into arguments?
我假设给出了这行代码:
Promise.all(array).then(foo)
Promise.all
使用Function.call
来调用foo
,
foo.call(foo, arrayValues)
我想将foo
修改为foo.apply
函数,以便使用值数组调用它将其拆分为常规参数。
这是我的思路......
假设我有这个功能
function test(a,b,c){
console.log(a,b,c)
}
我可以使用call
和apply
test.call(null,1,2,3)
>> 1 2 3
test.apply(null,[1,2,3])
>> 1 2 3
到目前为止一切顺利,这也有效......
test.call.apply(test,[null,1,2,3])
>> 1 2 3
但是我不能让这个工作
test.apply.call(test,[null,1,2,3])
>> undefined undefined undefined
这里发生了什么?
答案 0 :(得分:1)
我得到了它的工作
test.apply.call(test,null,[1,2,3])
>> 1 2 3
答案 1 :(得分:1)
test.apply.call(test,[null,1,2,3])
等于
test.apply([null,1,2,3])
等于
test()
所以你得到了未定义的输出。
test.apply.call(test,null,[1,2,3])
等于
test.apply(null,[1,2,3])
等于
test(1,2,3)
这是对的。