Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否可以调用数组索引之类的TypeScript方法?_Javascript_Oop_Typescript - Fatal编程技术网

Javascript 是否可以调用数组索引之类的TypeScript方法?

Javascript 是否可以调用数组索引之类的TypeScript方法?,javascript,oop,typescript,Javascript,Oop,Typescript,这是通过索引获取数组的方法: var theArray=[]; theArray['something']=="Hello!"; console.log(theArray['something']); //Print "Hello!" 现在想象同样的事情,我有一个函数,我要调用它;像这样: export class myClass { public callByIndex(theIndex:string) { //this is how it works:

这是通过索引获取数组的方法:

var theArray=[];
theArray['something']=="Hello!";
console.log(theArray['something']); //Print "Hello!"
现在想象同样的事情,我有一个函数,我要调用它;像这样:

export class myClass {
    public callByIndex(theIndex:string) {
        //this is how it works:
        this.doSomething()

        //And these are the ways I need to call them:
        this.theIndex //of course error!
        //or
        this[theIndex]; //Another Error! How to do it?
    }

    private doSomething (){
        console.log("Yesss, I called!");
    }
}

let callTest = new myClass();
callTest.callByIndex("doSomething"); //Here I give the method name!

这怎么可能呢?

首先,Javascript中的数组只是具有整数属性的普通对象(
{}
)。因此,要使用方括号调用函数,只需将要执行的函数的名称传递给它即可

class Test {
  dummyFunction(arg) {
    console.log('dummyFunction called with argument: ' + arg);
  }
}

let test = new Test();
test['dummyFunction']('this is a string');

什么索引?您需要对象/数组根据给定的索引获取值
this.someArray[theIndex]
@Oen44我知道你的意思,这就是为什么我问,我知道JavaScript对象/数组,这就是为什么我说“像数组索引”,我需要调用一些方法,比如我们如何通过它们的索引访问数组。明智的回答!伟大的如何从
dummyFunction
方法内部实现相同的事情?假设
Test
类有另一个方法,而
dummyFunction
arg
参数工作是根据给定的参数调用这些方法。(给定的参数是其他方法名称)然后在
dummyFunction
中执行
this[arg]()
以执行该特定函数,假设名称存储在
arg
中的函数没有argument@M98Javascript中的方括号实际上是一种属性访问语法,函数只是给定对象(或类型)的属性,方括号语法的好处在于它允许您向它传递任意表达式,如果它的计算结果不是解析为现有属性的值,
undefined
将返回。非常感谢您的精彩回答。它帮助我再次学到了新的东西。