我想对这个数组进行排序:
['Ramsey','丝芙兰','seq','ser','用户']
像这样:
如果我输入“Se”,它会对数组进行排序,以便包含“se”(小写或大写)的字符串在数组中排在第一位。
我怎么能这样做?
感谢。
答案 0 :(得分:1)
var array:Array = ['Ramsey', 'Sephora', 'seq', 'ser', 'user'];
trace( array.sort(Array.CASEINSENSITIVE) );
答案 1 :(得分:1)
从技术上讲,它们都包含“se”,因此您无需排序:)
如果要删除所有不包含“se”的元素,可以在以下位置调用数组filter()
:http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#filter()
然后按正常方式按字母顺序排序。您可能希望创建自己的过滤器,因为filter()
每次都会创建一个新数组。
如果要将对象保留在数组中,则需要实现自己的排序。这样的事情应该有效:
public function Test()
{
var a:Array = ['Ramsey', 'Sephora', 'seq', 'ser', 'user'];
trace( a ); // Ramsey,Sephora,seq,ser,user
a.sort( this._sort );
trace( a ); // Sephora,seq,ser,user,Ramsey
}
private function _sort( a:String, b:String ):int
{
// if they're the same we don't care
if ( a == b )
return 0;
// make them both lowercase
var aLower:String = a.toLowerCase();
var bLower:String = b.toLowerCase();
// see if they contain our string
var aIndex:int = aLower.indexOf( "se" );
var bIndex:int = bLower.indexOf( "se" );
// if one of them doesn't have it, set it afterwards
if ( aIndex == -1 && bIndex != -1 ) // a doesn't contain our string
return 1; // b before a
else if ( aIndex != -1 && bIndex == -1 ) // b doesn't contain our string
return -1; // a before b
else if ( aIndex == -1 && bIndex == -1 ) // neither contain our string
return ( aLower < bLower ) ? -1 : 1; // sort them alphabetically
else
{
// they both have "se"
// if a has "se" before b, set it in front
// otherwise if they're in the same place, sort alphabetically, or on
// length or any other way we want
if ( aIndex == bIndex )
return ( aLower < bLower ) ? -1 : 1;
return aIndex - bIndex;
}
}