AS3将String转换为Object

时间:2014-02-14 01:25:18

标签: actionscript-3

考虑到字符串中的对象存在,我正在尝试将后续字符串转换为对象:

var exampleStr:String = "myObject.property1.property2";
var exampleObj:Object = exampleStr as Object;

我如何实现这一目标,是否可以替代您提供的方法?

3 个答案:

答案 0 :(得分:1)

我认为你试图从汇编的字符串中动态创建一个对象?如果是这样,我认为你在寻找的是:

var exampleObj:Object = this[ "myObject.property1.property2" ];

这假设 myObject 的范围是“ this ”,而 property2 也是一个对象。

答案 1 :(得分:1)

   //Convert the string to  a property array       
    var t:Array = exampleStr.split(".");

    var exampleObj:Object = null;

    if (t.length > 0)
    {

        var objName:String = t[i];

        //get the object in the class
        exampleObj = this[objName];

        for (var i:int = 1; i < t.length; i++)
        {
            var propertyName:String = t[i];

            if (exampleObj.hasOwnProperty(propertyName))
            {
                exampleObj = exampleObj[propertyName];
            }
            else
            {
                break;
            }
        }
    }

答案 2 :(得分:1)

你可以使用这样一个简单的函数:

function getRValue(target:Object, chain:String):*
{
    for each(var i:String in chain.split("."))
    {
        if(target.hasOwnProperty(i)) target = target[i];
        else
        {
            // Couldn't find property.
            throw new Error("Property " + i + " does not exist.");
        }
    }


    return target;
}

通过测试:

var myObject:Object = {
    property1: {
        property2: "Hello world!"
    }
};

trace( getRValue(this, "myObject.property1.property2") ); // Hello world!
trace( getRValue(myObject, "property1.property2") ); // Hello world!