首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >排序数组AS3

排序数组AS3
EN

Stack Overflow用户
提问于 2012-03-25 23:34:19
回答 2查看 4.8K关注 0票数 0

我想对这个数组进行排序:

‘'Ramsey','Sephora','seq','ser','user’

如下所示:

如果我输入"Se“,它会对数组进行排序,因此包含"se”(小写或大写)的字符串在数组中排在第一位。

我怎么能这么做呢?

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-03-27 05:26:14

从技术上讲,它们都包含"se",所以您不需要排序:)

如果你想删除所有不包含"se“的元素,你可以在数组中调用filter()之前:http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#filter()

然后按照正常的字母顺序进行排序。您可能希望创建自己的筛选器,因为filter()每次都会创建一个新的数组。

如果您想将对象保留在数组中,那么您需要实现自己的排序。像这样的东西应该是有效的:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2012-03-25 23:48:23

代码语言:javascript
复制
var array:Array = ['Ramsey', 'Sephora', 'seq', 'ser', 'user'];

trace( array.sort(Array.CASEINSENSITIVE) );
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9861400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档