get string representation of a variable name in as3

本秂侑毒 提交于 2019-11-29 17:05:59

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
    }
}
joncys
  • 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.

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';

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!