2012-03-25 90 views
0

我倒是希望排序此数组:排序阵列AS3

[ '拉姆齐', '丝芙兰', '序列', 'SER', '用户']

像这样:

如果我键入“Se”,它会对数组进行排序,以便包含“se”(小写或大写)的字符串在数组中首先出现。

我该怎么做?

谢谢。

回答

1

技术上它们都含有“硒”,所以你如果要删除不包含“硒”的元素不需要排序:)

,您可以拨打filter()您的阵列之前:http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#filter()

然后按照字母顺序排序正常。您可能需要创建自己的过滤器,因为filter()每次都会创建一个新的Array。

如果你想保留数组中的对象,那么你需要实现自己的排序。像这样的东西应该工作:

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; 
    } 
} 
1
var array:Array = ['Ramsey', 'Sephora', 'seq', 'ser', 'user']; 

trace(array.sort(Array.CASEINSENSITIVE));