2012-03-25 126 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));