函数AS2内的动态变量名

时间:2012-07-25 09:53:14

标签: flash actionscript-2

我有以下问题:

我有一个接收多个变量的函数:

function test( fooValue:String, foobar1:String, foobar2:String, goobar1:String, goobar2:String ) {
//using the values statically
mytext1.text = foobar1;
mytext2.text = foobar2;
mytext3.text = goobar1;
mytext4.text = goobar2;

if ( goobar1 = "problem" ) {
    myProblem.text = this["foo" + fooValue] + this["goo" + fooValue];
}
}
//now here's an example call
test( "bar1","first value ","second value ", "another value", "yet another value");

鉴于fooValue在上面的调用中有“bar1”,我如何让myProblem.text显示“first value another value”

这个[“foo”+ fooValue]给了我未定义的

  • 编辑了问题并尝试更具体。

1 个答案:

答案 0 :(得分:1)

简单。

function test( fooValue:String, foobar1:String, foobar2:String, goobar1:String, goobar2:String ) {
//using the values statically
mytext1.text = foobar1;
mytext2.text = foobar2;
mytext3.text = goobar1;
mytext4.text = goobar2;

if ( goobar1 == "problem" ) {
    myProblem.text = this["foo" + fooValue] + this["goo" + fooValue];
}
}
//now here's an example call
test( "bar1","first value ","second value ", "another value", "yet another value")

注意改变?它是=行中的额外if(goobar1...

goobar1 = "problem"设置goobar1的值。

goobar1 == "problem"返回goobar1的值是否为“problem”

新秀的错误,有时候也是由有经验的人制造的:)

此外

this["foo" + fooValue]相当于this.foobar1(由于this对象没有任何名为foobar1的属性,因此无效

你这样做:

switch(fooValue) {
    case "bar1":
        myProblem.text = foobar1 + goobar1;
        break;
    case "bar2":
        myProblem.text = foobar2 + goobar2;
        break;
}