转自:http://elanso.com/ArticleModule/GJUpS4GJVIJhNOVwONLmPUIi.html
在前面的Flex中利用StringValidator类验证字符串合法性的例子中提到了字符串合法性的验证,接下来的例子演示了如何将字符串数组转化为对象数组从而使其在Flex中可以作为数据提供源来使用。
下面是完整代码:
Download: main.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:Script>
<![CDATA[
private var arrayOfString:Array;
private var arrayOfObject:Array;
private function init():void {
arrayOfString = ["test", "test", "fork", "test"];
arrayOfObject = stringArrayToObjectArray(arrayOfString);
}
private function stringArrayToObjectArray(sourceArray:Array, key:String = "label"):Array {
var returnArray:Array = new Array();
var idx:uint;
var len:uint = sourceArray.length;
for (idx=0; idx<len; idx++) {
var obj:Object = {};
obj[key] = sourceArray[idx];
returnArray.push(obj);
}
return returnArray;
}
]]>
</mx:Script>
<mx:ApplicationControlBar dock="true">
<mx:Button label="Array of String"
click="list.dataProvider = arrayOfString;" />
<mx:Button label="Array of Object"
click="list.dataProvider = arrayOfObject;" />
</mx:ApplicationControlBar>
<mx:List id="list"
width="100"
rowCount="6"
initialize="init();" />
</mx:Application>
在前面的Flex中利用StringValidator类验证字符串合法性的例子中提到了字符串合法性的验证,接下来的例子演示了如何将字符串数组转化为对象数组从而使其在Flex中可以作为数据提供源来使用。
下面是完整代码:
Download: main.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:Script>
<![CDATA[
private var arrayOfString:Array;
private var arrayOfObject:Array;
private function init():void {
arrayOfString = ["test", "test", "fork", "test"];
arrayOfObject = stringArrayToObjectArray(arrayOfString);
}
private function stringArrayToObjectArray(sourceArray:Array, key:String = "label"):Array {
var returnArray:Array = new Array();
var idx:uint;
var len:uint = sourceArray.length;
for (idx=0; idx<len; idx++) {
var obj:Object = {};
obj[key] = sourceArray[idx];
returnArray.push(obj);
}
return returnArray;
}
]]>
</mx:Script>
<mx:ApplicationControlBar dock="true">
<mx:Button label="Array of String"
click="list.dataProvider = arrayOfString;" />
<mx:Button label="Array of Object"
click="list.dataProvider = arrayOfObject;" />
</mx:ApplicationControlBar>
<mx:List id="list"
width="100"
rowCount="6"
initialize="init();" />
</mx:Application>