簡體   English   中英

JavaScript排序方法

[英]Javascript sort method

我正在網站上使用一些代碼,並且嘗試按成員ID排序結果(我在下面的代碼中留有注釋),但似乎沒有對結果的順序進行排序我一定做錯了什么。 有人知道問題出在哪里嗎,也許我如何將顯示的結果數量限制在10個左右?

var httpRequestObject = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Wcf/Search.svc/TestSearch",
dataType: "json",
success: function (response) {

    if (response != null && response.d != null) {
        var data = response.d;
        if (data.ServiceOperationOutcome == 10) {

            var profileList = data.MemberList;
            if (profileList != null && profileList.length > 0) {
                for (var i = 0; i < profileList.length; i++) {
                    var profile = profileList[i];

                    // sort var
                    var memberId = (profile.MemberId);


                    if (profile != null) {
                        var clonedTemplate = $('.profile-slider #profile').clone();
                        $(clonedTemplate).removeAttr('style').removeAttr('id');
                        $(clonedTemplate).find('img').attr("src", profile.ThumbnailUrl).attr("alt", profile.Nickname).wrap('<a></a>');
                        $(clonedTemplate).appendTo('.profile-slider');

                        // sort
                        $(memberId).sort();
                    }
                }

            }
        }

        else {
            alert("Error code " + String(data.ServiceOperationOutcome));
        }
    }

    else {
        alert("Null data");
    }
},

error: function (jqXHR, textStatus, errorThrown) {
    alert(errorThrown);
}

});

jQuery沒有排序方法,但是可能有您要查找的Array.sort() ,但是profile似乎是數組data.MemberList一個對象,因此您應該在迭代之前對其進行排序它:

var profileList = data.MemberList; // array
profileList.sort(function(a,b) {
    return a.MemberId.localeCompare(b.MemberId);
});

for (var i = 0; i < profileList.length; i++) {
   // do stuff to each item in the now sorted array
}

正如adeneo所說,您可能想對“成員”列表進行排序。

profileList = profileList
  .filter(function (arg) {return arg !== null;}) // remove nulls
  .sort(function(a, b) {
    return a.MemberId < b.MemberId ? -1 : 1; // the < operator works for numbers or strings
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM