对象数组排序–jQuery数组和字符串
http://mmz06.blog.163.com/blog/static/12141696201102935021258/
对象数组排序
说明:
sort()方法:需要添加比较函数,反复从数组中获取一对值,在比较的基础上返回<0、=0和>0的值。
其实和排序字符串、数值没什么区别,比较对象是按照对象中的某个属性比较,所以,我们只要取出对象中的某个属性比较即可。
对象数组排序
说明:
sort()方法:需要添加比较函数,反复从数组中获取一对值,在比较的基础上返回<0、=0和>0的值。
其实和排序字符串、数值没什么区别,比较对象是按照对象中的某个属性比较,所以,我们只要取出对象中的某个属性比较即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
Html代码 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>jQuery数组和字符串--对象数组排序</title> <script type="text/javascript" src="rs/js/jquery.js"></script> <script type="text/javascript"> <!-- $( function() { var students =[ {'sid':'ST001','sname':'张三','sage':18}, {'sid':'ST004','sname':'赵六','sage':23}, {'sid':'ST002','sname':'李四','sage':42}, {'sid':'ST003','sname':'王五','sage':35} ]; //表格显示 $.each(students, function(index, value) { $('#ia').append('<tr><td>' + value.sid + '</td><td>' + value.sname + '</td><td>' + value.sage + '</td></tr>'); } ); //按照SID排序 var sidOrder = students.sort( function(a, b) { if(a.sid < b.sid) return -1; if(a.sid > b.sid) return 1; return 0; } ); $.each(sidOrder, function(index, value) { $('#ib').append('<tr><td>' + value.sid + '</td><td>' + value.sname + '</td><td>' + value.sage + '</td></tr>') } ); //按照SAGE排序 var sageOrder = students.sort( function(a, b) { return (a.sage - b.sage); } ); $.each(sageOrder, function(index, value) { $('#ic').append('<tr><td>' + value.sid + '</td><td>' + value.sname + '</td><td>' + value.sage + '</td></tr>') } ); } ); //--> </script> </head> <body> <h5>未排序对象数组:</h5> <table id='ia' border="1"></table> <h5>按照SID排序对象数组:</h5> <table id='ib' border="1"></table> <h5>按照SAGE排序对象数组:</h5> <table id='ic' border="1"></table> </body> </html> |