JS数组根据属性来实现排序

var data = [{
    name: "zhao",
    age: 22
  }, {
    name: "qian",
    age: 21
  }, {
    name: "sun",
    age: 25
  }];
  //定义一个比较器
  function compare(propertyName,asc) {
    return function(a,b){  
           return asc?  ~~(a[propertyName] > b[propertyName]):~~(a[propertyName] < b[propertyName]) ;  
    }  
  }
  //使用方法
  data.sort(compare("age"));
  console.log(data);

 

posted @ 2017-04-10 15:18  杨浪  阅读(764)  评论(0编辑  收藏  举报