按年龄大小排序的例子 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <button onclick="sortByAgeDesc()">按年龄从大到小排序</button> <div id="list"></div> </body> <script> var data = [{name: "Zachary", age: 28}, {name: "Nicholas", age:29}]; renderList(data); /*按属性排序的通用方法*/ function createComparisonFunction( propertyName ){ var result = function( object1, object2){ var value1 = object1[propertyName]; var value2 = object2[propertyName]; if(value1 < value2){ return -1; }else if(value1 > value2){ return 1; }else{ return 0; }; }; return result; }; /*渲染列表内容*/ function renderList( data ){ var _html = ‘‘; for(var i = 0, l = data.length; i < l; i++){ _html += ‘<li>姓名:‘+ data[i].name +‘,年龄:‘+ data[i].age +‘</li>‘; }; document.getElementById(‘list‘).innerHTML = ‘<ul>‘+ _html +‘</ul>‘; }; /*按年龄排序*/ function sortByAgeDesc(){ data.sort( createComparisonFunction("name")); renderList( data ); return false; }; </script> </html>
时间: 2024-10-28 17:05:23