1

我想要一种最多存储三个字符串的方法。当我得到一个新的时,我想将它添加到列表的底部并从列表的顶部删除一个(最旧的)。

我知道这可以用双端队列在 python 中完成,但不确定如何在 AS3 中实现它或者它是否已经存在。谷歌搜索在 googlecode 上找到了一些代码,但没有编译。

4

2 回答 2

5

您可以将字符串存储在数组向量中

大批

unshift() - 将一个或多个元素添加到数组的开头并返回数组的新长度。数组中的其他元素从它们的原始位置 i 移动到 i+1。

pop() - 从数组中删除最后一个元素并返回该元素的值。

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"

所以在你的情况下:

“我想将它添加到列表的底部,并从列表顶部删除一个(最旧的)。”

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)

您将在数组中有 3 个字符串,您可以像这样访问它们:

trace( arr[0] );  //first element
trace( arr[1] );  //second element
trace( arr[2] );  //third element

向量

因为您只想存储字符串,所以可以使用Vector以获得更好的性能。

简而言之,Vector Class 是一个“类型化数组”,具有与 Array 类似的方法。

您的情况的唯一区别是声明:

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 
于 2013-06-03T14:28:03.400 回答
1

我想一个合适的解决方案是使用一个数组来存储你的字符串,然后使用 pop 和 unshift 来删除和添加项目。

例如

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);

}
于 2013-06-03T14:27:23.517 回答