【问题标题】:jquery sorting complex static objectjquery排序复杂的静态对象
【发布时间】:2009-03-09 19:45:38
【问题描述】:

我想对方法的键或名称进行排序..以下是对象http://pastie.org/411854

【问题讨论】:

    标签: javascript object


    【解决方案1】:

    如果我理解正确,您想根据键名或方法名(相同的值)对成员进行排序吗?这对 Object 没有意义,因为成员没有顺序。

    但是,如果您将这些对象放在这样的数组中:

    var apiDocs = [
        {
            "methodName": "friendsGetByUser",
            "methodDescription": "Returns user ids of friends of the specified user.",
            ...
        }, {
            "methodName": "friendsGetBestFriends",
            "methodDescription": "Returns user ids of best friends of the logged in user.",
            ...
        }
        ...
    ];
    

    然后您可以通过调用 Array.sort 传入比较函数来轻松地对数组进行排序。

    apiDocs.sort(function (a, b) {
            return a.methodName < b.methodName;
        });
    

    【讨论】:

      【解决方案2】:

      要获得函数名称的排序数组,您可以使用以下命令:

      var functions = [];
      for(functionName in apiDocs) {
        functions.push(functionName);
      }
      functions.sort();
      

      如果您想执行某种更复杂的排序,您可以按照以下方式进行操作

      var functions = [];
      for(functionName in apiDocs) {
        functions.push(apiDocs[functionName]);
      }
      functions.sort(//put sorting closure here)
      

      您可以在此处获取有关自定义排序的更多信息:Array Sorting Explained

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-07
        • 1970-01-01
        • 1970-01-01
        • 2011-04-12
        • 2011-09-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多