是否可以将输入数组扩展为参数? [英] Is it possible to spread the input array into arguments?
问题描述
假设我有这个功能:
function printData(a, b,c){
console.log(a,b,c)
}
我想要
Promise.all([1,2,3])。然后(printData)
>> [1,2,3] undefined undefined
要打印,
>> 1 2 3
有没有更好的方式这样做:
Promise.all([1,2,3,4])然后(function(values){printData.apply(null,values)})
使用spread运算符
/ p>
Promise.all([1,2,3])然后(printData.apply)
但它返回错误
尝试使用传播操作员技术上有你的嵌套功能,这是有效的,但有另一种方式
Promise.all([1,2 ,3])然后(printData.apply)
无效,因为这等于:
printData.apply.call(undefined,[1,2,3])
它返回相同的错误
>>未捕获TypeError:Function。 prototype.apply被叫做未定义的
这是一个未定义而不是函数
承诺
通过此
到调用
,并且它失去了应该是什么的跟踪。
你想要的是:
test.apply.call(test,[null,1,2,3] )
等于:
test.apply(null,[1,2,3])
这等于
test(1,2,3)
因为您无法控制Promise使用调用,请使用 bind
来确定参数
printData.apply.bind(printData,null)
当被调用等于
printData.apply.bind(printData,null).call(undefined, [1,2,3])
>> 1 2 3
so最后:
Promise.all([1,2,3])。然后(printData.apply.bind(printData,null))
>> 1 2 3
这是一个有关组合应用和调用
为什么我不能调用function.apply?
So Promise.all passes an array as a value into the function, I would much rather it pass the array values as arguments.
Assume I have this function:
function printData(a,b,c){
console.log(a,b,c)
}
I would like
Promise.all([1,2,3]).then(printData)
>> [1,2,3] undefined undefined
To print this instead
>> 1 2 3
Is there a better way of doing this:
Promise.all([1,2,3,4]).then(function(values){printData.apply(null, values)})
using the spread operator?
I also tried
Promise.all([1,2,3]).then(printData.apply)
But it returns an error
Trying to use the spread operator technically has you nesting functions, which works, but there is another way
Promise.all([1,2,3]).then(printData.apply)
Doesn't work because this is equal to:
printData.apply.call(undefined, [1,2,3])
which returns the same error
>>Uncaught TypeError: Function.prototype.apply was called on undefined,
which is a undefined and not a function
Promise
passes this
in to call
and it loses track of what it should be.
What you want is:
test.apply.call(test,[null,1,2,3])
which equals:
test.apply(null,[1,2,3])
which equals
test(1,2,3)
because you don't have control over Promise using call, use bind
to determine the arguments
printData.apply.bind(printData, null)
which when called equals
printData.apply.bind(printData, null).call(undefined, [1,2,3])
>> 1 2 3
so Finally:
Promise.all([1,2,3]).then(printData.apply.bind(printData,null))
>> 1 2 3
Here's a related question about combining apply and call Why can I not call a function.apply?
这篇关于是否可以将输入数组扩展为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!