我想对这个数组进行排序:
‘'Ramsey','Sephora','seq','ser','user’
如下所示:
如果我输入"Se“,它会对数组进行排序,因此包含"se”(小写或大写)的字符串在数组中排在第一位。
我怎么能这么做呢?
谢谢。
发布于 2012-03-27 05:26:14
从技术上讲,它们都包含"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;
}
}发布于 2012-03-25 23:48:23
var array:Array = ['Ramsey', 'Sephora', 'seq', 'ser', 'user'];
trace( array.sort(Array.CASEINSENSITIVE) );https://stackoverflow.com/questions/9861400
复制相似问题