js中对象的自定义排序
1 //并返回一个可以用来对包含该成员的对象数组进行排序的比较函数 2 var compareAsc = function (prop) { 3 return function (obj1, obj2) { 4 var val1 = obj1[prop]; 5 var val2 = obj2[prop]; 6 if (!isNaN(Number(val1)) && !isNaN(Number(val2))) { 7 val1 = Number(val1); 8 val2 = Number(val2); 9 } 10 if (val1 < val2) { 11 return -1; 12 } else if (val1 > val2) { 13 return 1; 14 } else { 15 return 0; 16 } 17 } 18 } 19 var compareDesc = function (prop) { 20 return function (obj1, obj2) { 21 var val1 = obj1[prop]; 22 var val2 = obj2[prop]; 23 if (!isNaN(Number(val1)) && !isNaN(Number(val2))) { 24 val1 = Number(val1); 25 val2 = Number(val2); 26 } 27 if (val1 > val2) { 28 return -1; 29 } else if (val1 < val2) { 30 return 1; 31 } else { 32 return 0; 33 } 34 } 35 }
原始js中的排序不能满足:
arr.sort(sortNumber);
arr.sort(function (a, b) {
return b.name < a.name;
});
商城列表-积分由高到低由低到高排列:
1 $scope.up=true; 2 $scope.down = false; 3 $scope.upDown = function(i) { 4 $scope.up=!$scope.up; 5 $scope.down=!$scope.down 6 if($scope.up == true && $scope.down == false){ 7 intData.sort(compareAsc("price")); 8 }else if($scope.up == false && $scope.down == true){ 9 intData.sort(compareDesc("price")); 10 } 11 };
html:
<a class="col col-50" ng-click="upDown()">{{'jifen.sortUp' | i18next}} <i ng-class="{'ion-ios-arrow-thin-up':up,'ion-ios-arrow-thin-down':down }" class="icon "></i></a>
参考:http://www.jb51.net/article/67458.htm