按对象指定字段排序(升序)示例:
var element1 = {title : "mytitle1", orderIndex : 0};
var element2 = {title : "mytitle2", orderIndex : 1};
var array = new Array();
array.push(element1);
array.push(element2);
//根据orderIndex字段对arrayOrder数组进行排序
var arrayOrder = array.sort(function (a, b) {
return (a.orderIndex - b.orderIndex);
});
$.each(arrayOrder, function (index, element) {
//遍历arrayOrder数组,通过element.title和element.orderIndex得到数组中元素的属性
});
具体示例:
1. 需求:按orderIndex规定的顺序进行课程的学习和考试。根据API返回的数据动态生成表格。要实现的样式如下:
API返回的数据格式和含义如下:
{ "id": <String>,//学习任务Id "planName": <String>,//学习任务名称 "studyPlanStages": [ { "title": <String>,//阶段名称 "userKnowledges": [ { "title": <String>,//课程标题 "progress": <double>,//课程的学习进度 "orderIndex": <int>,//课程在这一阶段的排序号 "studyHours": <int>,//总学习时长 "actualStudyHours": <String>//实际学习时长 } ], "examResults": [ { "name": <String>,//考试名称 "status": <int>,//考试状态,0-未开始,2-已结束 "isPass": <int>,//是否通过考试,0-未通过,1-已通过 "score": <int>,//考试得分 "orderIndex": <int>//考试在这一阶段的排序号 } ] } ] }
因为课程和考试对象字段不一致,不方便排序,所以统一成自定义task对象后,展示根据orderIndex重新排序后的记录。
if (content.studyPlanStages != "") {
//遍历阶段列表
$.each(content.studyPlanStages, function (i, obj) {
var taskArray = new Array();
if (obj.userKnowledges != null) {
//遍历课程列表
$.each(obj.userKnowledges, function (i, item) {
var task = {
stageTitle : obj.title,//当前阶段的标题保存为stageTitle
title : item.title,//课程标题
progress : item.progress + "%",//课程学习进度百分比
actualStudyHours : "",
orderIndex : item.orderIndex//课程在当前阶段中的顺序
};
if (item.actualStudyHours != null && item.studyHours != null) {
task.actualStudyHours = item.actualStudyHours + "/" + item.studyHours;
}
taskArray.push(task);
});
}
if (obj.examResults != null) {
//遍历考试列表
$.each(obj.examResults, function (i, item) {
var task = {
stageTitle : obj.title,//当前阶段的标题保存为stageTitle
title : item.name,//考试标题
progress : "",
actualStudyHours : "",
orderIndex : item.orderIndex
};
if (item.status == 0) {
task.progress = "未开始";
} else if (item.status == 2) {//考试结束后,进度栏展示是否通过,学时栏展示成绩
task.progress = item.isPass == 1 ? "已通过" : "未通过";
task.actualStudyHours = "成绩:" + item.score;
}
taskArray.push(task);
});
}
//这里重新定义一个taskArrayOrder用于储存排序后的记录
var taskArrayOrder = taskArray;
taskArrayOrder = taskArray.sort(function(a, b) {
return (a.orderIndex - b.orderIndex);
});
$.each(taskArrayOrder, function(index, value){
$('#executorDetail').append('<tr><td>' + value.stageTitle +
'</td><td>' + value.title + '</td><td>' + value.progress +
'</td><td>' + value.actualStudyHours + '</td></tr>');
});
});
} else {
$("#executorDetail").append("<tr><td colspan='3'>内容为空</td></tr>");
}