I have the following string:
"2,26,17,33,6,14,9,29,1"
And an array of int
, usedIds
.
If I do:
private var usedIds:Array;
usedIds = "2,26,17,33,6,14,9,29,1".split(',');
I get an array of strings
.
How can I do it to get an array of 开发者_如何学编程int
?
The simplest way is using Linq:
int[] usedIds = "2,26,17,33,6,14,9,29,1".split(',').Select(x => int.Parse(x)).ToArray();
You could try this:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}// end function
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var string:String = "2,26,17,33,6,14,9,29,1";
var strings:Array = string.split(',');
var ints:Array = new Array();
for each(var s:String in strings)
{
ints.push(int(s));
}// end for each
trace(ints[0]) // output: 2
trace(ints[0] is int) // output: true
}// end function
}// end class
}// end package
[UPDATE]
A slightly shorter version of the above is:
var string:String = "2,26,17,33,6,14,9,29,1";
var ints:Array = new Array();
for each(var s:String in string.split(","))
{
ints.push(int(s));
}// end for each
trace(ints[0]) // output: 2
trace(ints[0] is int) // output: true
[UPDATE 2]
Shortest(don't recommend):
var ints:Array = [];
for each(var s:String in "2,26,17,33,6,14,9,29,1".split(",")) ints.push(int(s));
trace(ints[0]) // output: 2
trace(ints[0] is int) // output: true
An other example :
var a:Array = "2,26,17,33,6,14,9,29,1".split(",");
a.forEach(function(item:*, index:int, array:Array):void{
array[index] = int(item);
});
You might have to loop through your array and convert it (tested):
function splitToInt($input:String,$delimiter:String):Array
{
var inArr:Array = $input.split($delimiter);
var outArr:Array = [];
for each(var index in inArr) {
trace(index);
outArr.push(int(index));
}
return outArr;
}
var usedIds:Array = splitToInt("2,26,17,33,6,14,9,29,1",",");
精彩评论