Reputation: 2279
I would like a way to store upto three strings. When I get a new one, I want to add it to the bottom of the list and remove the one from the top of the list (the oldest one).
I know this can be done in python with a deque, but not sure how to implement it in AS3 or if it exsists already. The google search turned up some code on googlecode but it didn't compile.
Upvotes: 1
Views: 151
Reputation: 4530
You can store strings in an Array or Vector
unshift() - Adds one or more elements to the beginning of an array and returns the new length of the array. The other elements in the array are moved from their original position, i, to i+1.
pop() - Removes the last element from an array and returns the value of that element.
var arr: Array = [ "three", "four", "five" ];
arr.unshift( "two" );
trace( arr ); // "two", "three", "four", "five"
arr.unshift( "one" );
trace( arr ); // "one , ""two", "three", "four", "five"
arr.pop(); //Removes the last element
trace( arr ); // "one , ""two", "three", "four"
So in your case:
"I want to add it to the bottom of the list and remove the one from the top of the list (the oldest one)."
var arr: Array = [ "my", "three", "strings" ];
arr.unshift( "newString" ); //add it to the bottom of the list
arr.pop(); // remove the one from the top of the list (the oldest one)
You will have 3 strings in the array, and you can access them like this:
trace( arr[0] ); //first element
trace( arr[1] ); //second element
trace( arr[2] ); //third element
Because you want to store only Strings, you could use Vector for better performance.
Vector Class in short is a 'typed array' and has similar methods to Array.
The only difference in your case would be in declaration:
var vect: Vector.<String> = new <String>[ "my", "three", "strings" ];
vect.unshift( "newString" ); //add it to the bottom of the list
vect.pop(); // remove the one from the top of the list
Upvotes: 5
Reputation: 3851
I would imagine a suitable solution would be to use an array to store your strings in, then use pop and unshift to remove and add items.
e.g.
var _array:Array = [];
addNewString("string1");
addNewString("string2");
addNewString("string3");
addNewString("string4");
function addNewString(newString:String):void {
if (_array.length > 2) {
//if we have 3 items in the array, remove the last one
_array.pop();
}
//always add the newString to the front of the array
_array.unshift(newString);
trace("Current _array includes: "+_array);
}
Upvotes: 1