我正在网站上使用一些代码,我正在尝试按成员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);
}
});
答案 0 :(得分:3)
jQuery没有sort方法,但是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
}
答案 1 :(得分:3)
正如阿德内诺所说,你可能想要对会员名单进行排序。
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
});