可使用数组提供的sort()方法,需要传入比较函数,反复从数组中获取一对值,在比较的基础上返回<0、=0和>0的值。其实和排序字符串、数值没什么区别,比较对象是按照对象中的某个属性比较,所以,我们只要取出对象中的某个属性比较即可。
假设以对象数组形式来保存学生信息。每个学生包括3个属性:sid,sname,sage。
var students =[ {'sid':'ST001','sname':'张三','sage':18}, {'sid':'ST004','sname':'赵六','sage':23}, {'sid':'ST002','sname':'李四','sage':42}, {'sid':'ST003','sname':'王五','sage':35} ]; //按照SID排序,sidOrder即为按照sid排序后的对象数组 var sidOrder = students.sort( function(stu1, stu2) { if(stu1.sid < stu2.sid) return -1; if(stu1.sid > stu2.sid) return 1; return 0; } ); 以下为完整代码,并采用了对象的原型构建法来创建对象,封装了对象排序的比较方法的获取 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>对象数组排序</title> <script type="text/javascript" src="../jquery-3.2.1.js"></script> <script type="text/javascript"> function Student(sid,sname,sage){ this.sid = sid; this.sname = sname; this.sage = sage; } Student.getSortFunc = function(sortProperty){ var func = function(stu1,stu2){ var result = 0; if (sortProperty === "sid" || sortProperty === "sname") { if (stu1[sortProperty] < stu2[sortProperty]) { result = -1; } if (stu1[sortProperty] > stu2[sortProperty]) { result = 1; } } else if(sortProperty === "sage") { result = stu1[sortProperty] - stu2[sortProperty]; } return result; } return func; } function show(tblId,studentArr){ $.each(studentArr, function(index, value){ $('#'+tblId).append('<tr><td>' + value.sid + '</td><td>' + value.sname + '</td><td>' + value.sage + '</td></tr>') } ); } <!-- $(function(){ var students =[]; students.push(new Student('ST001','abc',18)); students.push(new Student('ST004','aAsdf',23)); students.push(new Student('ST002','asf',42)); students.push(new Student('ST003','bsdgf',35)); //表格显示 show("tbl1",students); //按照SID排序 show("tbl2",students.sort(Student.getSortFunc("sid"))); //按照SAGE排序 show("tbl3",students.sort(Student.getSortFunc("sage"))); //按照sname排序 show("tbl4",students.sort(Student.getSortFunc("sname"))); }); </script> </head> <body> <h5>未排序对象数组:</h5> <table id='tbl1' border="1" cellpadding="5px" cellspacing="0"></table> <h5>按照SID排序对象数组:</h5> <table id='tbl2' border="1" cellpadding="5px" cellspacing="0"></table> <h5>按照SAGE排序对象数组:</h5> <table id='tbl3' border="1" cellpadding="5px" cellspacing="0"></table> <h5>按照SNAME排序对象数组:</h5> <table id='tbl4' border="1" cellpadding="5px" cellspacing="0"></table> </body> </html>