在 TypeScript 中将数组作为参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20443101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing array as arguments in TypeScript
提问by langtu
I have two methods:
我有两种方法:
static m1(...args: any[]) {
//using args as array ...
}
static m2(str: string, ...args: any[]){
//do something
//....
//call to m1
m1(args);
}
The call to m1(1,2,3)
works as expect. However, the call m2("abc",1,2,3)
will pass to m1([1,2,3])
, not as expect: m1(1,2,3)
.
调用m1(1,2,3)
按预期工作。但是,调用m2("abc",1,2,3)
将传递到m1([1,2,3])
,而不是预期:m1(1,2,3)
。
So, how to pass args
as arguments when make call to m1
in m2
?
那么,如何args
在调用m1
in时作为参数传递m2
?
采纳答案by user703016
T.m1.apply(this, args);
Where T is the enclosing class of m1
.
其中 T 是 的封闭类m1
。
回答by Rick Love
Actually, using the ...
again when calling the method will work.
实际上,...
在调用该方法时再次使用该方法是可行的。
It generates the apply call for you in javascript.
它在 javascript 中为您生成应用调用。
static m1(...args: any[]) {
//using args as array ...
}
static m2(str: string, ...args: any[]){
//do something
//....
//call to m1
// m1(args);
// BECOMES
m1(...args);
}