在 TypeScript 中将数组作为参数传递 [英] Passing array as arguments in TypeScript

查看:62
本文介绍了在 TypeScript 中将数组作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种方法:

static m1(...args: any[]) {
    //using args as array ...
}

static m2(str: string, ...args: any[]){
    //do something
    //....

    //call to m1
    m1(args);
}

m1(1,2,3) 的调用按预期工作.但是,调用 m2("abc",1,2,3) 将传递给 m1([1,2,3]),而不是预期:m1(1,2,3).

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).

那么,在m2中调用m1时,如何将args作为参数传递?

So, how to pass args as arguments when make call to m1 in m2?

推荐答案

使用 Function.prototype.apply:

T.m1.apply(this, args);

其中 T 是 m1 的封闭类.

Where T is the enclosing class of m1.

这篇关于在 TypeScript 中将数组作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆