get string representation of a variable name in as3

后端 未结 4 1551
日久生厌
日久生厌 2020-12-22 10:52

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 d

相关标签:
4条回答
  • 2020-12-22 11:14

    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';
    
    0 讨论(0)
  • 2020-12-22 11:27

    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
    
    0 讨论(0)
  • 2020-12-22 11:28

    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
        }
    }
    
    0 讨论(0)
  • 2020-12-22 11:32
    • 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.

    0 讨论(0)
提交回复
热议问题