get string representation of a variable name in as

2019-01-29 03:02发布

any way of doing this is as3?

for example, if I have a var dog:String, how can I get "dog" out of that variable?

Looking into reflection to do this, but there's got to be an easier way

-- A

4条回答
放我归山
2楼-- · 2019-01-29 03:19

Sounds like you don't want to "get" the string representation of a variable name, but rather set the variable based on a string.

To set a variable that you have its name as a string you can do this:

this['dog'] = 'value of the dog var';
查看更多
Fickle 薄情
3楼-- · 2019-01-29 03:21

In your example I don't think there is a way to retrieve "dog" as a String.

However, if dog is a property of a dynamic Object, then you could use a function like this:

function getVarName(subject:*, value:*):String
{
    for(var i:String in subject)
    {
        if(subject[i] == value) return i;
    }

    return "";
}

This function can work in a scenario like this:

var holder:Object = {
    dog: "some awesome dog"
}

trace(getVarName(holder, "some awesome dog")); // dog
查看更多
地球回转人心会变
4楼-- · 2019-01-29 03:27

Hope this helps.

class A {
   var dog:String = "something";
   var cat:String = "eatdog";
}

function getVars(obj:*):void
{
    for(var i:* in obj){
        trace( i + " : " + obj[i]);
        // this will trace all properties of object.
        // dog : somthing
        // cat : eatdog
    }
}
查看更多
看我几分像从前
5楼-- · 2019-01-29 03:29
  • First of all if it's an instance of a custom class, you can override the toString() method.

  • If it's a property of the class, you can use this method — https://stackoverflow.com/posts/3781635/revisions

  • If it's a local variable, there is no way to get that name.

查看更多
登录 后发表回答