2011-01-01 8 views
0

AS3에서 다음과 같은 문제가 있습니다. 이 문자열이 있습니다. "prop1 : val1, prop2 : val2, ..."; 나는 이것을 분해하고 문자열을 파싱하여 {prop1 : "val1", prop2 : "val2"}와 같은 동적 객체를 얻고 싶습니다.문자열 목록에서 동적 속성 추가

간단한 방법은 문자열 값을 순환하고 어떻게 해결하려면

경우 (strProp1 == "prop1") = o.prop1 strVal1; if (strProp1 == "prop2") o.prop1 = strVal2;

내가 예상 한 속성 이름을 알고 있기 때문에이 방법이 저에게는 효과적이지만 우아한 해결책은 아닙니다. as3 (자바의 리플렉션 API와 비슷한)에 다른 방법이 있는지 궁금해서이 문제를 해결합니다.

답변

0

split, 새로운 오브젝트 사용하여 빠른 예 :

// function that will parse the string an return an object with 
// all field and value 
function parse(str:String):Object { 
// create a new object that will hold the fields created dynamically 
var o:Object = {}; 

// split the string from ',' character 
// this will return an array with string like propX:valX 
for each (var values:String in str.split(",")) { 
    // now split the resulting string from ':' character 
    // so you have an array with string propX and valX 
    var keyvalue:Array = values.split(":"); 
    // assign the key/value to the object 
    o[keyvalue[0]] = keyvalue[1]; 
} 
return o; 
} 

// usage example 
var str:String="prop1:val1,prop2:val2,prop3:val3"; 

var myObject:Object = parse(str); 

trace(myObject.prop2); // output val2 
0
//get an Array of the values 
var strData:Array = yourString.split(","); 

//create the object you want to populate 
var object:Object = {}; 

for(var i:int ; i < strData.length ; ++i) 
{ 
    //a substring containing property name & value 
    var valueString:String = strData[i]; 

    var dataArray:Array = valueString.split(":"); 

    obj[dataArray[0]] = dataArray[1]; 
}