1.普通排序
<script> var array =[11,3,14,6,7,9]; array.sort(function(a,b){ return a-b; }); alert(array); </script>
2.排序json数组中对象的某个字段
<script> var array = [ {name: ‘a‘, phone: "13", value: ‘val_4‘}, {name: ‘b‘, phone: "5", value: ‘val_3‘}, {name: ‘d‘, phone:"9", value: ‘val_2‘}, {name: ‘c‘, phone: "12" , value: ‘val_1‘}, {name: ‘c‘, phone: "44" , value: ‘val_1‘}, {name: ‘c‘, phone:"34" , value: ‘val_1‘}, {name: ‘c‘, phone: "54" , value: ‘val_1‘} ] array.sort(function(a,b){ return a["phone"]*1-b["phone"]*1; }); document.write(strhtml) </script>
3. 排序json数组中对象的某个字段带逗号
<script> var data = [ { ranking: 1, name: "Princeton University", count: "8,014"}, { ranking: 2, name: "Harvard University", count: "19,882"}, { ranking: 3, name: "Yale University", count: "12,109"}, { ranking: 4, name: "Columbia University", count: "23,606"}, { ranking: 4, name: "Stanford University", count: "18,136"}, { ranking: 4, name: "University of Chicago", count: "12,539"}, { ranking: 7, name: "Massachusetts Institute of Technology", count: "11,301"}, { ranking: 8, name: "Duke University", count: "15,465"}, { ranking: 8, name: "University of Pennsylvania", count: "21,358"}] data.sort(function(a,b){ return ((a["count"].replace(",",""))*1)-((b["count"].replace(",","")*1)); }); var strhtml=""; for(var i=0; i<data.length; i++) { strhtml += "<div class=‘item‘><p>"+data[i].ranking+"</p><p>"+data[i].name+"</p><p>"+data[i].count+"</p></div>"; } $(".table").append(strhtml); </script>
时间: 2024-12-15 08:44:41