1 <script> 2 var data=[{name:"121",age:"18",year:"2018"},{name:"132",age:"16",year:"2019"}] 3 /** 4 * 创建比较参数函数 5 * @param propertyName 属性名 6 * @returns {Function} 返回比较函数 7 */ 8 function compareFunction(propertyName){ 9 return function (src,tar) { 10 //获取比较的值 11 var v1=src[propertyName]; 12 var v2=tar[propertyName]; 13 if(v1>v2){ 14 return 1; 15 } 16 if(v1<v2){ 17 return -1; 18 } 19 return 0; 20 }; 21 } 22 //按照age进行比较 23 data.sort(compareFunction("age")); 24 alert(data[0].name); 25 //按照year进行比较 26 data.sort(compareFunction("year")); 27 alert(data[0].name) 28 </script>